JQuery querySelector: is there an option to select by class AND id?

I inherited the old jQuery code and I noticed that the original developer was using the ".class #id" query selector all over the place. For example:

 $('.red #mydiv')

      

Is it better, worse, or just the same as

 $('#mydiv')

      

And why? Why?

My curious mind is dying to know!

+3


source to share


5 answers


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.

+1


source


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.

+1


source


Ok if you want to grab the let say hover event for all elements with this class or this particular div then that would make sense. Remember that this is an OR condition, not an AND, so it depends on what you are trying to accomplish.

0


source


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.

0


source


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.

-1


source







All Articles