+ 1
Can you give me some examples with getElementsByClassName ?
I do not understand how to use
3 Respuestas
+ 11
unlike getElementById, getElementsByClassName returns a collection (basically an array) of the elements that were found in the DOM.
so accessing an element would be done by square brackets [ ] and an index
example:
given this html
<div class="numbers">1</div>
<div class="numbers">2</div>
<div class="numbers">3</div>
if you want to change the color of the number 2 to green, you can do something like this in JS
var number_2 = document.getElementsByClassName("numbers")[1];
number_2.style.color = "green";
+ 4
"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.
Example
Get all elements with the specified class name:
var x =document.getElementsByClassName("example");"
Source: https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
+ 3
Thanks a lot