Javascript class selection

Why is this javascript selector

document.getElementsByClassName('first-class class-child second-child')

looks identical to this jQuery selector

 $('.first-class .class-chlid .second-child'); 

but doesn't it work the same?

+6
source share
4 answers

getElementsByClassName will select an element that has all these classes separated by spaces. Instead, use the querySelectorAll method, which helps you select elements based on the CSS selector.

 document.querySelectorAll('.first-class .class-chlid .second-child'); 
+9
source

It looks like you are looking for document.querySelector() and / or document.querySelectorAll() :

 var matches = document.querySelectorAll(".first-class .class-chlid .second-child"); 

Note that this will not be identical to jQuery in the sense that the return value does not have a free API for applying changes / effects / etc. for all matched items. What you get here is just an array of matched elements. You can do what you want with this array.

+6
source

The getElementsByClassName function returns an array-like object of all children that have all the specified class names.

If you want to "walk" to the dom-tree (just like jQuery does), you should use the querySelectorAll function

 document.querySelectorAll('.first-class .class-child .second-child') 
+3
source

It is unclear if you are looking for equivalent javascript or equivalent jquery (even if the answer is already accepted to make this distinction, if anyone else comes up with this question, they may look for the opposite):

The opposite also applies since you can change jquery to match getElementsByClassName (rather than change to querySelectorAll in javascript)

This code:

 document.getElementsByClassName('first-class class-child second-child') 

returns a massive object of all child elements that have all the specified class names (MDN)

In jquery equivalent:

  $('.first-class.class-child.second-child'); 

which finds all elements that have all the specified class names.

If you want to find elements with any of these class names, use a comma:

  $('.first-class,.class-child,.second-child'); 
+2
source

Source: https://habr.com/ru/post/1013193/


All Articles