I have two divs with same class.
<div class="html-code"></div>
<div class="html-code"></div>
I added JavaScript to the class. I took variable like this.
var html = document.getElementsByClassName("html-code")[0];
It is so strange that the JavaScript I functioned on the variable html is applying only to the first div but not second. What could be the problem? Thanks in advance.
Remove the index [0] from the end to select all divs, like this.
var html = document.getElementsByClassName("html-code");
or use a loop like this:
var html = document.getElementsByClassName("html-code"); for (i in html) { html[i].innerHTML = "div " + i; }
<div class="html-code"></div> <div class="html-code"></div>
You can try out this way:
var html = document.getElementsByClassName("html-code"); Array.prototype.forEach.call(html, function(el) { el.style.backgroundColor = "green"; });
.html-code { width: 100px; height: 100px; margin-bottom: 2px; border: 1px solid #ccc; }
<div class="html-code"></div> <div class="html-code"></div>
To answer you question, when you do this:
document.getElementsByClassName("html-code");
The response is a array-like object called HTMLCollection then
document.getElementsByClassName("html-code")[0]//<-- first element
document.getElementsByClassName("html-code")[1]//<-- second element
Because the class html-code
has two matches in this case.
To iterate over the elements you can't use the array methods like .map()
or filter()
you should use methods used for objects:
for(var element in object) {//code}
or the generic:
for(let i; i<object.length;i++){//code}
and methods using the Object constructor , like:
var keys = Object.keys(object);
Thank you for your help.
I finally solved the problem by adding two variables and also two functions.
var html = document.getElementsByClassName("html-
code")[0];
html.onclick = function() {
// My JavaScript function
}
var html = document.getElementsByClassName("html-
code")[1];
html.onclick = function() {
// Same function as above
}
This is working for me. I understood that if there are two divs with same class, we have to add two functions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.