Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements by class name? [duplicate]

Tags:

javascript

How to get all elements by class name on pure javascript ? Analog $('.class') in Jquery ?

like image 416
Bdfy Avatar asked Feb 24 '12 08:02

Bdfy


People also ask

How do you get all elements with the same class name?

The querySelectorAll() method returns all elements within the document having the same class. To get the first element that matches the specified selector, you can use the querySelector() method.

What is used to find all HTML elements with the same class name?

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.

How do you get all elements with the same class react?

To find all elements by className in React: Use the getElementsByClassName method to get all elements with a specific class.

Can you use the same class name on multiple elements?

The HTML class attribute is used to specify a class for an HTML element. Multiple HTML elements can share the same class.


Video Answer


2 Answers

A Simple and an easy way

var cusid_ele = document.getElementsByClassName('custid'); for (var i = 0; i < cusid_ele.length; ++i) {     var item = cusid_ele[i];       item.innerHTML = 'this is value'; } 
like image 32
kta Avatar answered Sep 30 '22 11:09

kta


document.getElementsByClassName(klass)

Be aware that some engines (particularly the older browsers) don't have it. You might consider using a shim, if that's the case. It will be slow, and iterate over the whole document, but it will work.

EDIT several years later: You can get the same result using document.querySelectorAll('.klass'), which doesn't seem like much, but the latter allows queries on any CSS selector, which makes it much more flexible, in case "get all elements by class name" is just a step in what you are really trying to do, and is the vanilla JS answer to jQuery's $('.class').

like image 166
Amadan Avatar answered Sep 30 '22 10:09

Amadan