+ 4
I don't know what i am doing wrong here if u know correct me... Here's the code
<!DOCTYPE html> <html> <head> <title> examples</title> </head> <body> <div id="demo"> <p> HI</p> </div> <div class="waste"> <p>Mmmmm</p> </div> </body> <script type="text/javascript"> var ex=document.getElementById("demo"); ex.innerHTML="Helloo"; var exer=document.getElementsByClassName("waste"); exer.innerHTML="friends"; </script> </html>
5 Antworten
+ 5
getElementsByClassName
^As you can see, it says ELEMENTS, which is plural. When you're dealing with an ID, it's referencing a singular element. When you use classes, you're references multiple elements at the same time. As such, it's stored as an array because it's multiple elements that are being stored. That's why we have to iterate through it so that we can apply it to all of the elements for that class.
+ 4
why we have to use array when we using the getElementsByClassName?!?
+ 4
Fata1 Err0r thank u so much😘now I am completely understand....👍👍
+ 4
@Arjun
You're more than welcome bro! Glad that helped you out. When you have the time, invest into learning jQuery. It greatly simplifies and adds a lot of really cool features to Javascript. I'd pick it over vanilla Javascript every day of the week.
+ 3
1. Move your <script> to the bottom of your <body>
2. Since you're getting a list of all "waste" class elements, you'll want to iterate through that array in order to change it. Otherwise, just specify which index it is if you know it (or if it's only one, it'll be 0).
3. Although not necessary in this example, I wrapped my script inside of 'window.onload' so that our script loads AFTER our page fully loads. In some instances our scripts can load before the elements on the page even exist, which will throw off your scripts and cause issues; this will help prevent such occurrences.
https://code.sololearn.com/W153wPfeeFIo/#html
<!DOCTYPE html>
<html>
<head>
<title> examples</title>
</head>
<body>
<div id="demo">
<p>
HI</p>
</div>
<div class="waste">
<p>Mmmmm</p>
</div>
<script type="text/javascript">
window.onload = function(){
var ex=document.getElementById("demo");
ex.innerHTML="Hellooooo";
var exer=document.getElementsByClassName("waste");
for(el in exer){
exer[el].innerHTML = "Friends!";
}
}
</script>
</body>
</html>
:::: OUTPUT :::::
Hellooooo
Friends!