I wanted to get a list of DOM elements by class name and tag name in JavaScript, not using jQuery.
For example I need to get all <ul>
elements with class .active
var elements = document.getElementsByTagName("ul");
var activeElements = document.getElementsByClassName('active')
What is the fastest and best way to do this in JavaScript.
No external libraries like jQuery or cheerio
Use the element. classList. contains() method to check if an element contains a specific class name.
The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.
We can find an element using the element tag name with Selenium webdriver with the help of locator tagname. To locate an element with tagname, we have to use the By. tagName method. In the above image, the text – You are browsing the best resources for has the h4 tag.
We want to get the unique element and allocate it in a variable this can be done by making use of getElementById. But when we want to get all the products elements and allocate them in a variable then basically we are using getElementByClassName.
document.querySelectorAll('ul.active')
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