javascript - find sametype elements and change bgcolor from element id . - sample

<!DOCTYPE html>
<html>
<body>

<p  id="green">This is a p element</p>

<p  id="yellow">This is also a p element.</p>

<p   id="blue">This is also a p element - Click the button to change the background color of all p elements in this document.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var myNodelist = document.getElementsByTagName("p");
    var i;
    var clr;
    for (i = 0; i < myNodelist.length; i++) {
           clr =  myNodelist[i].id;
        myNodelist[i].style.backgroundColor = clr;
    }
}
</script>

</body>
</html>

Yorumlar