简体   繁体   中英

is it possible that getElementsByTagName doesn't actually return all the elements?

I know this is silly but i really don't understand what is going on, i am calling a simple getElementsByTagName from my js like this :

var script_elements = document.getElementsByTagName('script');
//then i loop
for(a = 0; a < script_elements.length ; a++)
{
     alert(script_elements[a].getAttribute('src'));
}

but it doesn't alert all the script elements with src defined that exists, i thought probably the document isn't fully loaded that is why i was having this problem, and to be sure i added in the beginning before calling getElementsByTagName this document.getElementsByTagName('html')[0].innerHTML and i do get the source code and nothing is missing, the only solution i found is to use regex and capture what i want but it is pretty dumb considering that JS has simple built in methods.

thanks in advance.

I was waiting for someone to do the honors and thus accept it, but since none did i will do it as it might help others, so thanks a lot to you guys the $(document).ready() did it :

$(document).ready(

    var script_elements = document.getElementsByTagName('script');
    for(a = 0; a < script_elements.length ; a++)
    {
       //treatment
    }

)

From my experience, getElementsByTagName always returns all elements but alert does not always show an alert. I would use console.log instead of alert. That will always log the element.

I am curious about using getAttribute instead of the src property of the element. I don't have a good reason for this, but I don't use getAttribute when there is a property in the dom that will work as well. Put another way, I only use getAttribute to access attributes that I define and the dom knows nothing about. My point is that I am weak on what getAttribute will return for the src attribute in every case, but I know that console.log will tell you, even if it is null which alert will not do (in my experience, I have not read the spec, so I do not know what alert is supposed to do)

For those concerned that you have to wait for the document to load, that is not my experience. Unless you put defer on the script tag, scripts load in sequence. As long as this script occurs in the document after the scripts that you want to inspect, you will see them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM