What do querySelectorAll and getElementsBy* methods return?Hide element by class in pure JavascriptgetElementsByClassName not workingHow to trigger click event using JavaScript on querySelectorAllHow to use getElementsByClassName in javascript-function?getElementsByClassName onclick issuegetElementsByClassName produces error “undefined”getElementsByClassName is not a function in FirefoxgetElementsByClassName to change the style of elements when event occursWhat is wrong with this getElementsByClassName call in Javascript?getElementsByTagName is not a functionWhat is the most efficient way to deep clone an object in JavaScript?What is the scope of variables in JavaScript?What is the !! (not not) operator in JavaScript?What is the JavaScript version of sleep()?What does “use strict” do in JavaScript, and what is the reasoning behind it?event.preventDefault() vs. return falseWhat is the 'new' keyword in JavaScript?What is the difference between call and apply?What is JSONP, and why was it created?How do I return the response from an asynchronous call?
Is there any set of 2-6 notes that doesn't have a chord name?
Pull-up sequence accumulator counter
Fedora boot screen shows both Fedora logo and Lenovo logo. Why and How?
How can Charles Proxy change settings without admin rights after first time?
Do French speakers not use the subjunctive informally?
"It will become the talk of Paris" - translation into French
Can a US president have someone sent to prison?
Layout of complex table
Every infinite linearly ordered set has two disjoint infinite subsets
Does the Paladin's Aura of Protection affect only either her or ONE ally in range?
Do equal angles necessarily mean a polygon is regular?
Counting occurrence of words in table is slow
A player is constantly pestering me about rules, what do I do as a DM?
First-year PhD giving a talk among well-established researchers in the field
Should I hide continue button until tasks are completed?
Mount a folder with a space on Linux
Do sudoku answers always have a single minimal clue set?
Is adding a new player (or players) a DM decision, or a group decision?
Why does the numerical solution of an ODE move away from an unstable equilibrium?
How to perform Login Authentication at the client-side?
What are the penalties for overstaying in USA?
MH370 blackbox - is it still possible to retrieve data from it?
Correct spacing in the alignat*-environment
Why does the A-4 Skyhawk sit nose-up when on ground?
What do querySelectorAll and getElementsBy* methods return?
Hide element by class in pure JavascriptgetElementsByClassName not workingHow to trigger click event using JavaScript on querySelectorAllHow to use getElementsByClassName in javascript-function?getElementsByClassName onclick issuegetElementsByClassName produces error “undefined”getElementsByClassName is not a function in FirefoxgetElementsByClassName to change the style of elements when event occursWhat is wrong with this getElementsByClassName call in Javascript?getElementsByTagName is not a functionWhat is the most efficient way to deep clone an object in JavaScript?What is the scope of variables in JavaScript?What is the !! (not not) operator in JavaScript?What is the JavaScript version of sleep()?What does “use strict” do in JavaScript, and what is the reasoning behind it?event.preventDefault() vs. return falseWhat is the 'new' keyword in JavaScript?What is the difference between call and apply?What is JSONP, and why was it created?How do I return the response from an asynchronous call?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
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';
javascript getelementsbyclassname dom-traversal
add a comment |
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';
javascript getelementsbyclassname dom-traversal
32
The clue is, very much, in the name:getElementsByClassName()
implies a plural, whereasgetElementById()
implies a singular element item.
– David Thomas
May 21 '12 at 23:20
1
I get that, it just didn't make sense to me that you can't change all the elements with that class name using the code above instead of having to loop through an array. jquery way is much better, i was just curious about the js way
– dmo
May 22 '12 at 4:34
1
Might be useful too: stackoverflow.com/questions/3871547/…
– kapa
Jul 31 '14 at 9:19
add a comment |
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';
javascript getelementsbyclassname dom-traversal
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';
javascript getelementsbyclassname dom-traversal
javascript getelementsbyclassname dom-traversal
edited Jan 7 at 12:37
rv7
2,5441 gold badge4 silver badges25 bronze badges
2,5441 gold badge4 silver badges25 bronze badges
asked May 21 '12 at 23:17
dmodmo
2,1673 gold badges15 silver badges22 bronze badges
2,1673 gold badges15 silver badges22 bronze badges
32
The clue is, very much, in the name:getElementsByClassName()
implies a plural, whereasgetElementById()
implies a singular element item.
– David Thomas
May 21 '12 at 23:20
1
I get that, it just didn't make sense to me that you can't change all the elements with that class name using the code above instead of having to loop through an array. jquery way is much better, i was just curious about the js way
– dmo
May 22 '12 at 4:34
1
Might be useful too: stackoverflow.com/questions/3871547/…
– kapa
Jul 31 '14 at 9:19
add a comment |
32
The clue is, very much, in the name:getElementsByClassName()
implies a plural, whereasgetElementById()
implies a singular element item.
– David Thomas
May 21 '12 at 23:20
1
I get that, it just didn't make sense to me that you can't change all the elements with that class name using the code above instead of having to loop through an array. jquery way is much better, i was just curious about the js way
– dmo
May 22 '12 at 4:34
1
Might be useful too: stackoverflow.com/questions/3871547/…
– kapa
Jul 31 '14 at 9:19
32
32
The clue is, very much, in the name:
getElementsByClassName()
implies a plural, whereas getElementById()
implies a singular element item.– David Thomas
May 21 '12 at 23:20
The clue is, very much, in the name:
getElementsByClassName()
implies a plural, whereas getElementById()
implies a singular element item.– David Thomas
May 21 '12 at 23:20
1
1
I get that, it just didn't make sense to me that you can't change all the elements with that class name using the code above instead of having to loop through an array. jquery way is much better, i was just curious about the js way
– dmo
May 22 '12 at 4:34
I get that, it just didn't make sense to me that you can't change all the elements with that class name using the code above instead of having to loop through an array. jquery way is much better, i was just curious about the js way
– dmo
May 22 '12 at 4:34
1
1
Might be useful too: stackoverflow.com/questions/3871547/…
– kapa
Jul 31 '14 at 9:19
Might be useful too: stackoverflow.com/questions/3871547/…
– kapa
Jul 31 '14 at 9:19
add a comment |
9 Answers
9
active
oldest
votes
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');
1
Does that also apply to<iframe>
which is also part of your domain
– JMASTER B
Sep 1 '16 at 1:25
2
It's 2018... Just create a wrapper function forquerySelectorAll()
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")
– user2437417
Apr 26 '18 at 20:40
1
"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.
– CoryCoolguy
May 8 at 18:38
add a comment |
You are using a array as an object, the difference between getElementbyId
and getElementsByClassName
is that:
getElementbyId
will return you an object.getElementsByClassName
will return you an array.
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.
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
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.
add a comment |
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.
add a comment |
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>
add a comment |
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 todocument.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 todocument.getElementsByClassName()
for classes anddocument.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
add a comment |
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);
add a comment |
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';
);
add a comment |
/*
* 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
add a comment |
With ES5+ (any browsed nowadays - 2017) you should be able to do
[].forEach.call(document.getElementsByClassName('answer'), function(el)
el.style.color= 'red';
);
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10693845%2fwhat-do-queryselectorall-and-getelementsby-methods-return%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
9 Answers
9
active
oldest
votes
9 Answers
9
active
oldest
votes
active
oldest
votes
active
oldest
votes
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');
1
Does that also apply to<iframe>
which is also part of your domain
– JMASTER B
Sep 1 '16 at 1:25
2
It's 2018... Just create a wrapper function forquerySelectorAll()
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")
– user2437417
Apr 26 '18 at 20:40
1
"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.
– CoryCoolguy
May 8 at 18:38
add a comment |
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');
1
Does that also apply to<iframe>
which is also part of your domain
– JMASTER B
Sep 1 '16 at 1:25
2
It's 2018... Just create a wrapper function forquerySelectorAll()
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")
– user2437417
Apr 26 '18 at 20:40
1
"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.
– CoryCoolguy
May 8 at 18:38
add a comment |
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');
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');
edited Aug 5 '17 at 8:59
Makyen
21.6k8 gold badges48 silver badges83 bronze badges
21.6k8 gold badges48 silver badges83 bronze badges
answered May 21 '12 at 23:18
ThiefMasterThiefMaster
246k63 gold badges486 silver badges568 bronze badges
246k63 gold badges486 silver badges568 bronze badges
1
Does that also apply to<iframe>
which is also part of your domain
– JMASTER B
Sep 1 '16 at 1:25
2
It's 2018... Just create a wrapper function forquerySelectorAll()
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")
– user2437417
Apr 26 '18 at 20:40
1
"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.
– CoryCoolguy
May 8 at 18:38
add a comment |
1
Does that also apply to<iframe>
which is also part of your domain
– JMASTER B
Sep 1 '16 at 1:25
2
It's 2018... Just create a wrapper function forquerySelectorAll()
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")
– user2437417
Apr 26 '18 at 20:40
1
"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.
– CoryCoolguy
May 8 at 18:38
1
1
Does that also apply to
<iframe>
which is also part of your domain– JMASTER B
Sep 1 '16 at 1:25
Does that also apply to
<iframe>
which is also part of your domain– JMASTER B
Sep 1 '16 at 1:25
2
2
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")
– user2437417
Apr 26 '18 at 20:40
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")
– user2437417
Apr 26 '18 at 20:40
1
1
"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.
– CoryCoolguy
May 8 at 18:38
"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.
– CoryCoolguy
May 8 at 18:38
add a comment |
You are using a array as an object, the difference between getElementbyId
and getElementsByClassName
is that:
getElementbyId
will return you an object.getElementsByClassName
will return you an array.
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.
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
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.
add a comment |
You are using a array as an object, the difference between getElementbyId
and getElementsByClassName
is that:
getElementbyId
will return you an object.getElementsByClassName
will return you an array.
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.
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
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.
add a comment |
You are using a array as an object, the difference between getElementbyId
and getElementsByClassName
is that:
getElementbyId
will return you an object.getElementsByClassName
will return you an array.
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.
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
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.
You are using a array as an object, the difference between getElementbyId
and getElementsByClassName
is that:
getElementbyId
will return you an object.getElementsByClassName
will return you an array.
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.
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
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.
edited May 6 at 0:59
Jeff
541 silver badge9 bronze badges
541 silver badge9 bronze badges
answered Feb 15 '16 at 2:53
Alvaro JoaoAlvaro Joao
5,1546 gold badges30 silver badges56 bronze badges
5,1546 gold badges30 silver badges56 bronze badges
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited May 23 '17 at 11:47
Community♦
11 silver badge
11 silver badge
answered Jan 7 '16 at 9:14
remdevtecremdevtec
2,4131 gold badge11 silver badges22 bronze badges
2,4131 gold badge11 silver badges22 bronze badges
add a comment |
add a comment |
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>
add a comment |
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>
add a comment |
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>
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>
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>
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>
$('.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>
$('.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>
edited Apr 4 '17 at 9:21
answered Feb 21 '17 at 23:07
kind userkind user
21k5 gold badges27 silver badges45 bronze badges
21k5 gold badges27 silver badges45 bronze badges
add a comment |
add a comment |
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 todocument.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 todocument.getElementsByClassName()
for classes anddocument.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
add a comment |
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 todocument.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 todocument.getElementsByClassName()
for classes anddocument.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
add a comment |
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 todocument.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 todocument.getElementsByClassName()
for classes anddocument.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
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 todocument.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 todocument.getElementsByClassName()
for classes anddocument.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
edited Mar 19 '18 at 15:01
answered Oct 23 '17 at 11:41
ThieliciousThielicious
2,21815 silver badges23 bronze badges
2,21815 silver badges23 bronze badges
add a comment |
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
answered Jun 17 '16 at 3:21
atilkanatilkan
2,41519 silver badges31 bronze badges
2,41519 silver badges31 bronze badges
add a comment |
add a comment |
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';
);
add a comment |
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';
);
add a comment |
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';
);
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';
);
edited Jul 2 '17 at 21:06
JJJ
29.4k15 gold badges78 silver badges93 bronze badges
29.4k15 gold badges78 silver badges93 bronze badges
answered Jul 2 '17 at 19:29
Sergey Sergey
1731 silver badge4 bronze badges
1731 silver badge4 bronze badges
add a comment |
add a comment |
/*
* 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
add a comment |
/*
* 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
add a comment |
/*
* 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
/*
* 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
answered Nov 25 '18 at 4:06
Irina MityugovaIrina Mityugova
411 bronze badge
411 bronze badge
add a comment |
add a comment |
With ES5+ (any browsed nowadays - 2017) you should be able to do
[].forEach.call(document.getElementsByClassName('answer'), function(el)
el.style.color= 'red';
);
add a comment |
With ES5+ (any browsed nowadays - 2017) you should be able to do
[].forEach.call(document.getElementsByClassName('answer'), function(el)
el.style.color= 'red';
);
add a comment |
With ES5+ (any browsed nowadays - 2017) you should be able to do
[].forEach.call(document.getElementsByClassName('answer'), function(el)
el.style.color= 'red';
);
With ES5+ (any browsed nowadays - 2017) you should be able to do
[].forEach.call(document.getElementsByClassName('answer'), function(el)
el.style.color= 'red';
);
[].forEach.call(document.getElementsByClassName('answer'), function(el)
el.style.color= 'red';
);
[].forEach.call(document.getElementsByClassName('answer'), function(el)
el.style.color= 'red';
);
edited Dec 2 '16 at 8:39
answered Apr 20 '15 at 16:03
Matas VaitkeviciusMatas Vaitkevicius
35.8k17 gold badges173 silver badges182 bronze badges
35.8k17 gold badges173 silver badges182 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10693845%2fwhat-do-queryselectorall-and-getelementsby-methods-return%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
32
The clue is, very much, in the name:
getElementsByClassName()
implies a plural, whereasgetElementById()
implies a singular element item.– David Thomas
May 21 '12 at 23:20
1
I get that, it just didn't make sense to me that you can't change all the elements with that class name using the code above instead of having to loop through an array. jquery way is much better, i was just curious about the js way
– dmo
May 22 '12 at 4:34
1
Might be useful too: stackoverflow.com/questions/3871547/…
– kapa
Jul 31 '14 at 9:19