thesksamim
thesksamim

Reputation: 17

problem between getElementById vs getElementsByTagName

I am getting a problem. When I apply a same rule using getElementById and getElementsByTagName , its perform differently

function sk(){
    var samim = document.getElementById("demo");
    
    for(var x=0; x<samim.length; x++){
        samim[x].innerHTML= "new text" ;
    }
}
setTimeout(sk,1000);

In the above code i am not able to get "new text". But when i write the code below I get "new tex" as usual. So where's the difference ?

function sk(){
    var samim = document.getElementsByTagName("p");
    
    for(var x=0; x<samim.length; x++){
        samim[x].innerHTML= "new text" ;
    }
}
setTimeout(sk,1000);

Upvotes: 0

Views: 57

Answers (1)

njain
njain

Reputation: 157

There can be two things like you are not having any div with id="p". One other thing you can consider is, .getElementsByTagName() returns an array of objects, while .getElementById() returns an object, So when you are doing : samim[x].innerHTML= "new text" ; then it is working on array of index so it works fine.But it 'getElementById ' this cannot work like this

For more exact answer can you share your html?

Upvotes: 1

Related Questions