ObiHill
ObiHill

Reputation: 11876

Getting the script tag using getElementsByTagName inconsistent across browsers

I have the following code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        var script_obj = document.getElementsByTagName('script')
        alert(typeof script_obj);
    });
</script>

When I run this in Firefox (v21) and Chrome (v29) I get object as the result, but in Safari (v5) I get function.

Why is this?!

In the rest of my script I'm iterating through script_obj to get the .src data, but my count function that determines the length of the haystack (i.e. script_obj) has a check that returns false if the haystack is not an array or an object, so it is failing in Safari. Is there another way I can do this instead of using document.getElementsByTagName('script')?!

Upvotes: 1

Views: 386

Answers (1)

ithcy
ithcy

Reputation: 5589

document.getElementsByTagName() returns a NodeList. Although a NodeList is not an Array, it does have a length property just like an Array. So you don't need to do anything special to count the number of items in it. Not sure what your count function is doing, but you can just do this:

> var script_obj = document.getElementsByTagName('script');
> alert(script_obj.length); // will alert '22' or whatever

Upvotes: 2

Related Questions