How to get element by class name? [duplicate]

2019-01-01 05:45发布

问题:

This question already has an answer here:

  • How to Get Element By Class in JavaScript? 10 answers

Using JavaScript, we can get element by id using following syntax:

var x=document.getElementById(\"by_id\");

I tried following to get element by class:

var y=document.getElementByClass(\"by_class\");

But it resulted into error:

getElementByClass is not function

How can I get an element by its class?

回答1:

The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.

The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:

var y = document.getElementsByClassName(\'foo\');
var aNode = y[0];

If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:

var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB\'s comment:
var arrFromList = [].slice.call(y);

As yckart suggested querySelector(\'.foo\') and querySelectorAll(\'.foo\') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:

  • querySelector(all)
  • getElementsByClassName
  • Don\'t use w3schools to learn something
  • Refer to MDN for accurate information


回答2:

Another option is to use, querySelector(\'.foo\') or querySelectorAll(\'.foo\') which has a broader browser support than getElementsByClassName.

http://caniuse.com/#feat=queryselector

http://caniuse.com/#feat=getelementsbyclassname



回答3:

You need to use the document.getElementsByClassName(\'class_name\');

and dont forget that the returned value is an array of elements so if you want the first one use:

document.getElementsByClassName(\'class_name\')[0]



回答4:

you can use

getElementsByClassName

suppose you have some elements and applied a class name \'test\', so, you can get elements like as following

var tests = document.getElementsByClassName(\'test\');

its returns an instance NodeList, or its superset: HTMLCollection (FF).

Read more