By dmo


2012-05-21 23:17:15 8 Comments

Do getElementsByClassName (and similar functions like getElementsByTagName and querySelectorAll) work the same as getElementById or do they return an array of elements?

The reason I ask is because I am trying to change the style of all elements using getElementsByClassName. See below.

//doesn't work
document.getElementsByClassName('myElement').style.size = '100px';

//works
document.getElementById('myIdElement').style.size = '100px';

9 comments

@Alvaro Joao 2016-02-15 02:53:10

You are using a array as an object, the difference between getElementbyId and getElementsByClassName is that:

  • getElementbyId will return an Element object or null if no element with the ID is found
  • getElementsByClassName will return a live HTMLCollection, possibly of length 0 if no matching elements are found

getElementsByClassName

The getElementsByClassName(classNames) method takes a string that contains an unordered set of unique space-separated tokens representing classes. When called, the method must return a live NodeList object containing all the elements in the document that have all the classes specified in that argument, having obtained the classes by splitting a string on spaces. If there are no tokens specified in the argument, then the method must return an empty NodeList.

https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname

getElementById

The getElementById() method accesses the first element with the specified id.

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

in your code the lines:

1- document.getElementsByClassName('myElement').style.size = '100px';

will NOT work as expected, because the getElementByClassName will return an array, and the array will NOT have the style property, you can access each element by iterating through them.

That's why the function getElementById worked for you, this function will return the direct object. Therefore you will be able to access the style property.

@Kaiido 2019-11-18 01:46:51

Note that the whatwg specs that are being implemented by the browsers do differ from the w3c ones here, the former (and hence current browsers) return an HTMLCollection for getElementsByClassName, not a NodeList. Minor, but may confuse some.

@RobG 2019-11-18 03:06:46

@Kaiido—the practical difference being…? To my understanding, a NodeList is a generic collection of DOM elements and is available in any DOM, not just an HTML DOM (e.g. an XML DOM), whereas an HTMLCollection is for HTML DOMs (obviously). The only difference I can see is the namedItem method of an HTMLCollection.

@RobG 2019-11-18 03:16:07

PS Nit pick: link for the WHATWG HTML Living Standard and the W3C HTML 5.2 standard. Spoilt by choice. ;-) Makes no difference to the point you raised though.

@Kaiido 2019-11-18 03:19:16

@RobG NodeList has many methods that are not accessible on HTMLCollection.

@RobG 2019-11-18 03:33:14

@Kaiido—sure, but forEach isn't specified as part of the interface for either collection or NodeList by W3C or WHATWG, it's specified separately, e.g. as a property of generic collections in the Web IDL specification so should apply to both collections and NodeLists (though I accept your point that the collection returned by getElementsByClassName doesn't have a forEach method). I guess the bottom line is that there's enough of a story for a good answer to tell it. :-)

@Kaiido 2019-11-18 03:44:05

@RobG I don't get your point really... I said it's "minor", though I had to make the correction because of your edit, and then to point at the discrepancy my own edit made between the quote used by Alvaro Joao, and the edited sentence. Yes, NodeList do have ArrayLike methods because their <Node> attr is iterable

@Irina Mityugova 2018-11-25 04:06:32

/*
 * To hide all elements with the same class, 
 * use looping to reach each element with that class. 
 * In this case, looping is done recursively
 */

const hideAll = (className, i=0) => {
if(!document.getElementsByClassName(className)[i]){ //exits the loop when element of that id does not exist
  return; 
}

document.getElementsByClassName(className)[i].style.visibility = 'hidden'; //hide element
return hideAll(className, i+1) //loop for the next element
}

hideAll('appBanner') //the function call requires the class name

@Thielicious 2017-10-23 11:41:11

In Other Words

  • document.querySelector() selects only the first one element of the specified selector. So it doesn't spit out an array, it's a single value. Similar to document.getElementById() which fetches ID-elements only, since IDs have to be unique.

  • document.querySelectorAll() selects all elements with the specified selector and returns them in an array. Similar to document.getElementsByClassName() for classes and document.getElementsByTagName() tags only.


Why use querySelector?

It's used merely for the sole purpose of ease and brevity.


Why use getElement/sBy?*

Faster performance.


Why this performance difference?

Both ways of selection has the purpose of creating a NodeList for further use. querySelectors generates a static NodeList with the selectors thus it must be first created from scratch.
getElement/sBy* immediately adapts the existing live NodeList of the current DOM.

So, when to use which method it's up to you/your project/your device.


Infos

Demo of all methods
NodeList Documentation
Performance Test

@ThiefMaster 2012-05-21 23:18:23

Your getElementById() code works since IDs have to be unique and thus the function always returns exactly one element (or null if none was found).

However, getElementsByClassName(), querySelectorAll(), and other getElementsBy* methods return an array-like collection of elements. Iterate over it like you would with a real array:

var elems = document.getElementsByClassName('myElement');
for(var i = 0; i < elems.length; i++) {
    elems[i].style.size = '100px';
}

If you prefer something shorter, consider using jQuery:

$('.myElement').css('size', '100px');

@JMASTER B 2016-09-01 01:25:16

Does that also apply to <iframe> which is also part of your domain

@user2437417 2018-04-26 20:40:09

It's 2018... Just create a wrapper function for querySelectorAll() and you can have nice short code without a large, old-school dependency. qSA(".myElement").forEach(el => el.style.size = "100px") Maybe have the wrapper receive a callback. qSA(".myElement", el => el.style.size = "100px")

@CoryCoolguy 2019-05-08 18:38:32

"If you prefer something shorter, consider adding a huge library to your project" I know 2012 was a different time, but even then I would've found that bit to be ludicrous.

@RobG 2019-11-18 02:54:04

"Iterate over it like you would with a real array… Careful, getElementsByClassName returns a live NodeList that might be unexpectedly modified during the loop, e.g. if the classname that they were selected by is removed. ;-)

@Sergey 2017-07-02 19:29:34

You could get a single element by running

document.querySelector('.myElement').style.size = '100px';

but it's going to work for the first element with class .myElement.

If you would like apply this for all elements with the class I suggest you to use

document.querySelectorAll('.myElement').forEach(function(element) {
    element.style.size = '100px';
});

@kind user 2017-02-21 23:07:39

ES6 provides Array.from() method, which creates a new Array instance from an array-like or iterable object.

let boxes = document.getElementsByClassName('box');

Array.from(boxes).forEach(v => v.style.background = 'green');
console.log(Array.from(boxes));
.box {
  width: 50px;
  height: 50px;
  margin: 5px;
  background: blue;
  display: inline-block;
}
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>

As you can see inside the code snippet, after using Array.from() function you are then able to manipulate over each element.


The same solution using jQuery.

$('.box').css({'background':'green'});
.box {
  width: 50px;
  height: 50px;
  margin: 5px;
  background: blue;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>

@Matas Vaitkevicius 2015-04-20 16:03:36

With ES5+ (any browsed nowadays - 2017) you should be able to do

[].forEach.call(document.getElementsByClassName('answer'), function(el) {
    el.style.color= 'red';
});

@atilkan 2016-06-17 03:21:49

It returns Array-like list.

You make that an Array as example

var el = getElementsByClassName("elem");
el = Array.prototype.slice.call(el); //this line
el[0].appendChild(otherElem);  

@remdevtec 2016-01-07 09:14:12

The following description is taken from this page:

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.

Tip: You can use the length property of the NodeList object to determine the number of elements with a specified class name, then you can loop through all elements and extract the info you want.

So, as a parameter getElementsByClassName would accept a class name.

If this is your HTML body:

<div id="first" class="menuItem"></div>
<div id="second" class="menuItem"></div>
<div id="third" class="menuItem"></div>
<div id="footer"></div>

then var menuItems = document.getElementsByClassName('menuItem') would return a collection (not an array) of the 3 upper <div>s, as they match the given class name.

You can then iterate over this nodes (<div>s in this case) collection with:

for (var menuItemIndex = 0 ; menuItems.length ; menuItemIndex ++) {
   var currentMenuItem = menuItems[menuItemIndex];
   // do stuff with currentMenuItem as a node.
}

Please refer to this post for more on differences between elements and nodes.

Related Questions

Sponsored Content

75 Answered Questions

[SOLVED] What is the JavaScript version of sleep()?

  • 2009-06-04 14:41:10
  • fmsf
  • 2396645 View
  • 2102 Score
  • 75 Answer
  • Tags:   javascript sleep

36 Answered Questions

[SOLVED] What is the !! (not not) operator in JavaScript?

  • 2009-04-24 08:13:58
  • Hexagon Theory
  • 504196 View
  • 2893 Score
  • 36 Answer
  • Tags:   javascript operators

24 Answered Questions

[SOLVED] What is the scope of variables in JavaScript?

36 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

21 Answered Questions

[SOLVED] What is the difference between call and apply?

69 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

13 Answered Questions

[SOLVED] event.preventDefault() vs. return false

9 Answered Questions

[SOLVED] What is JSONP, and why was it created?

14 Answered Questions

[SOLVED] What is the 'new' keyword in JavaScript?

Sponsored Content