In "demo" div I want to show getAttribute id and style of all elements (in this case two elements demone and demotwo). If I remove the loop then only the first elements id and style are displayed and everything works normally. As soon as I add the loop stops working, where I'm wrong.
function myFunction() {
var divs = document.querySelectorAll('*'),
i;
for (i = 0; i < divs.length; ++i) {
var div = divs[i];
var id = document.getElementById(div).getAttribute("id");
var sty = document.getElementById(div).getAttribute("style");
document.getElementById("demo").innerHTML = "Id element: " + id + " Style element: " + sty + "";
}
}
<div id="demoone" style="width:50px;height:60px;">One</div>
<div id="demotwo" style="width:30px;height:40px;">Two</div>
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>
querySelectorAll()
doesn't return IDs, it returns the elements themselves. So you don't need to callgetElementById()
before getting the attribute.If you want to see the info for all the elements, you need to append the message to the DIV's HTML, not overwrite it each time through the loop.