JQuery querySelector: is there an option to select by class AND id?
The fastest way is to use the ID: $('#mydiv')
or selector document.getElementById("mydiv")
.
What you might consider in your particular case (if the author of this code really knew what he was doing) is that perhaps the jQuery code is generic across the means:
- The same jQuery code is processed across all pages
-
#mydiv
may appear on multiple pages, but in different places - on some pages inside
.red
- Ask only when
#mydiv
appears inside.red
so
$('.red #mydiv').text("Hello, World!")
page1.html
<div class="red">
<div id="mydiv">Hello, World!</div>
</div>
page2.html
<div class="blue">
<div id="mydiv"></div>
</div>
adds an extra selector specificity to the selector.
source to share
It is best to use only one identifier. However, there are valid uses for the ancestor class preceding the identifier.
For example, consider an end pattern that sets up different classes in the body depending on which route is currently being used. An identifier can exist in all routes, but you can only do something specific to it if that body class exists.
source to share
It probably depends on what you are trying to do.
In CSS, class attributes are usually for many elements that must inherit certain styles, whereas id attributes are for one specific element that must inherit certain styles.
It really isn't a performance issue; it is a matter of whether you need the attributes to be set by the class selector .red
, or if all that was needed was an identifier myDiv
. Also, if there is any other Javascript or JQuery code that selects and identifies elements based on their IDs or class attributes, then that code might need one of them.
Keep in mind that an identifier is meant to be used by only one element, while MANY elements can have a class, and in fact, elements often have multiple classes.
source to share
I guess there are many answers to this question.
First answer: If your code uses selectors like this, your buddy might be doing it wrong by targeting one unique element twice. The second answer would be, it has bad html. And he should do that. Third answer: it has multiple elements on the page doing the same action.
source to share