0

What's wrong in JavaScript code?

I was checking code from Sololearn tutorial about DOM in JavaScript, where it says how to get element. I wanted to do same thing, but it always writes, that variable, which has element is not function, but in example I see same thing, but it is correct. Why?? <p class="name">Hello</p> var ob = document.getElementByClassName("name"); document.ob.innerHTML("Hi"); https://code.sololearn.com/WtG45tA5QvyE/?ref=app

16th Apr 2020, 9:35 PM
Anisimov David
Anisimov David - avatar
9 odpowiedzi
+ 3
the error...you have a typo...var ob = document.getElementByClassName("name"); ...it should be..elements not element... (plural) function test(){ var ob = document.getElementsByClassName("name"); ob[0].innerHTML = "Hoi"; } Then call the function by some event...onload...onmouseover etc.
16th Apr 2020, 10:31 PM
rodwynnejones
rodwynnejones - avatar
0
document.ob.innerHTML = "Some text"; I think the problem is that
16th Apr 2020, 9:38 PM
Saad Saleem
Saad Saleem - avatar
0
But it says that something wrong with variable
16th Apr 2020, 9:39 PM
Anisimov David
Anisimov David - avatar
0
Plz post your code here or just try By changing it I tell you above
16th Apr 2020, 9:41 PM
Saad Saleem
Saad Saleem - avatar
0
So, what is wrong?
16th Apr 2020, 9:50 PM
Anisimov David
Anisimov David - avatar
0
It says it's not a function because it is getElementsByClassName ,notice the s after Element ,it returns collection of html elements as an array with the specified class name ,so you need to access that element like you do in any array ,by specifying it's position like ob[0].innerHTML,also you need to assign it value like ob[0].innerHTML="hoi";
16th Apr 2020, 10:27 PM
Abhay
Abhay - avatar
0
Like this window.onload=function(){ var ob = document.getElementsByClassName("name"); ob[0].innerHTML="Hoi"; }
16th Apr 2020, 10:29 PM
Abhay
Abhay - avatar
0
window.onload means run the function that is basically script inside it after HTML has been loaded ,try without it you will get undefined error because script may run before html gets loaded
16th Apr 2020, 10:32 PM
Abhay
Abhay - avatar
0
Also I recommend to use querySelector instead of getElementsByClassName if you just want to select that particular class only ,like document.querySelector(".name");
16th Apr 2020, 10:33 PM
Abhay
Abhay - avatar