<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Finding elements by ID</title> </head> <body> <h1 id="heading">All about dogs</h1> <p>The domestic <span class="animal">dog</span> is known as man's best friend. The <span class="animal">dog</span> was the first domesticated animal and has been widely kept as a working, hunting, and pet companion. According to recent coarse estimates, there are currently between 700 million and one billion <span class="animal">dog</span>s, making them the most abundant predators in the world. <a href="http://en.wikipedia.org/wiki/Dog">Read more on Wikipedia</a>.</p> <img src="https://www.kasandbox.org/programming-images/animals/dog_sleeping-puppy.png" height="150" alt="Sleeping puppy"> <img src="https://www.kasandbox.org/programming-images/animals/dogs_collies.png" height="150" alt="Dogs running"> <script> var headingEl = document.getElementById("heading"); console.log(headingEl); headingEl.innerHTML="all about cat" var nameEls = document.getElementsByClassName ("animal"); console.log(nameEls[0]); for (var i = 0; i < nameEls.length; i++) { nameEls[i].innerHTML = "cat"; } </script> </body> </html>
add for bawah document.getElementsByClassName("animal"); untuk dapatkan semua class yang ada tag animal
var nameEls = document.getElementsByClassName("animal"); console.log(nameEls); for (var i = 0; i < nameEls.length; i++) { nameEls[i].innerHTML = "cat"; }
<body> <div class="name-tag"> <h1>Hello, my name is...</h1> <p>Grace Hopper</p> </div> <div class="name-tag"> <h1>Hello, my name is...</h1> <p>Alan Turing</p> </div> <script> var namaKuEls = document.getElementsByTagName("h1"); for (var i = 0; i < namaKuEls.length; i++) { namaKuEls[i].innerHTML = "Muhaza"; } </script> </body>
//rujuk : https://www.khanacademy.org/computing/computer-programming/html-css-js/html-js-dom-access/p/finding-multiple-dom-elements-by-tag-or-class-name