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
9 Respuestas
+ 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.
0
document.ob.innerHTML = "Some text";
I think the problem is that
0
But it says that something wrong with variable
0
Plz post your code here or just try
By changing it I tell you above
0
So, what is wrong?
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";
0
Like this
window.onload=function(){
var ob = document.getElementsByClassName("name");
ob[0].innerHTML="Hoi";
}
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
0
Also I recommend to use querySelector instead of getElementsByClassName if you just want to select that particular class only ,like
document.querySelector(".name");