Why does "undefined" occur even when defining the exact element to be reached?

2

I'm applying a injection in the address bar of the web browser , on the page of a video on youtube, in which I want to extract the date of the posting of the same.

If we open this link we see a div similar to this:

Whenweselectthepostdateandthenusethe"View Selection Source" tool available in the web browser itself, we can see the source code for the selected line:

Giventhenameoftheclasswatch-time-text,Itriedthefollowing:

javascript:postado=document.getElementsByClassName("watch-time-text").innerHTML; alert(postado);

And the following occurred:

Whydoesthisundefinedevenoccuronthepage?

Becauseagifisworthathousandwords

    
asked by anonymous 25.02.2017 / 17:21

1 answer

6

The getElementsByClassName method returns a collection of elements and not one element only.

If you are sure that there is only one element with this class you can use index 0 to get it.

postado = document.getElementsByClassName("watch-time-text")[0].innerHTML;
alert(postado);
    
25.02.2017 / 17:32