<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<form action="" class="js-form">
<fieldset>
<div>
<label><input type="radio" name="s"/></label>
<label><input type="radio" name="s"/></label>
<label><input type="radio" name="s"/></label>
<label><input type="radio" name="s"/></label>
<label><input type="radio" name="s"/></label>
<label><input type="radio" name="s"/></label>
</div>
</fieldset>
</form>
var customForms = document.querySelectorAll(".js-form");
var customFormLabels;
var customFormLabelSiblings;
for (var customForm of customForms) {
customFormLabels = customForm.querySelectorAll("label");
for (var label of customFormLabels) {
label.addEventListener("click", function(e) {
customFormLabelSiblings = this.parentNode.querySelectorAll("label");
e.preventDefault();
for (var sibling of customFormLabelSiblings) {
sibling.classList.remove("is-active");
}
this.classList.add("is-active");
});
}
}
$(".js-form input").on("click", function() {
$(this).parent().siblings().removeClass("is-active");
$(this).parent().addClass("is-active");
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
vanilla | |
jQuery |
Test name | Executions per second |
---|---|
vanilla | 580.9 Ops/sec |
jQuery | 65139.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided benchmark compares two approaches to adding an active class to labels on click: jQuery and vanilla JavaScript. The test case is designed to measure the performance difference between these two methods.
Options Compared
Two options are being compared:
Pros and Cons of Each Approach
jQuery:
Pros:
Cons:
Vanilla JavaScript:
Pros:
Cons:
Library Used
In this benchmark, jQuery is used in its version 3.3.1.
Special JS Feature/Syntax
None are mentioned, so I won't elaborate on any special JavaScript features or syntax used in these test cases.
Other Alternatives
If you're interested in exploring alternative approaches to DOM manipulation, consider:
Keep in mind that each alternative has its own strengths, weaknesses, and trade-offs. The choice ultimately depends on your project's specific needs, your team's expertise, and your personal preferences.
In summary, this benchmark provides a straightforward comparison between jQuery and vanilla JavaScript approaches to adding an active class to labels on click. By understanding the pros and cons of each approach, you can make informed decisions when choosing between these options for your own projects.