Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get elements by class name and tag name

Tags:

javascript

dom

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

like image 322
svnm Avatar asked Aug 25 '15 01:08

svnm


People also ask

How do you find an element with a specific class name?

Use the element. classList. contains() method to check if an element contains a specific class name.

Can you get element by class in JavaScript?

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.

How do I find element by tag name?

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.

What is difference between getElementById and getElementsByClassName?

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.


1 Answers

document.querySelectorAll('ul.active')
like image 176
Amadan Avatar answered Nov 07 '22 07:11

Amadan