I've been thinking about why we cannot do this in javascript.
document.getElementsByClassName('class1').getElementsByClassName('class2')
This will not work, because the first getElementsByClassName
call will give us an HTMLCollection, which doesn't have getElementsByClassName
defined on it. Why is this? This would be a great function to use in this way, since it would let you get elements based on them having multiple different classes, not just one.
Is there any way to:
Iterate Through Elements Returned by getElementsByClassName getElementsByClassName method is to use the for-of loop. We call document. getElementsByClassName with 'slide' to return an HTML element collection object with all the divs. Then we use the for-of loop to loop through each item.
HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number. An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
getElementsByClassName() The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.
Get by multiple class names:
document.querySelector('.someclass.otherclass'); // get first element that matches
document.querySelectorAll('.someclass.otherclass'); //get all elements that match
You can querySelector*
any DOM element, not just document
, in order to search in it.
Get by class name in HTMLCollection
[].filter.call(
htmlCollection, element => [].includes.call(elements.classList, 'someclassname')
)
Neither HTMLCollection nor .classList
are arrays, only array-like objects, hence the need for .call
.
Get elements by class name in HTMLCollection :
HTMLCollection.prototype.forEach = Array.prototype.forEach;
HTMLCollection.prototype.getElementsByClassName = function( name ){
var all = [];
this.forEach( function( el ){
if( el )
all.concat( el.getElementsByClassName( name ) );
});
return all;
}
Get elements by multiple class names :
document.querySelectorAll('.class1.class2');
Please use the second for better performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With