getElementsByTagNameNS. Now I Know. And Knowing is Half the Battle.

Yesterday I was wondering why obj.getElementsByTagName wasn’t working in Safari/WebKit on a tag with a namespace prefix. I wondered, aloud, whether or not it was just something I was ignorant of.

It turns out that was the case. Dom Level 2 added new namespace specific methods to search through documents or document fragments for tags of a specific NameSpace. I’d just never had to use them before. Learning that greatly simplified the hacky code I wrote yesterday. Here it is, new and improved:

flickr : function(obj) {
var items = obj.getElementsByTagName("item");
if (items.length > 0 ) {
var blob = "<div id='flickrFeed'>";
for (var i = 0; i< 5 ; i++) {
var flink = items[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
//is getElementsByTagNameNS defined //I guess I should really test that it does what I expect it to do //on the off chance someone wrote their own in a library or something //I'm pretty sure of the environment this code will live in //so I'm going to throw caution to the wind and just check to see //if something of the name has been defined at the document level if ( document.getElementsByTagNameNS !== undefined ) {
//if it's there. Use it. //the first argument is the namespace itself, //the second is the tag. var flurl = items[i].getElementsByTagNameNS("http://search.yahoo.com/mrss/","thumbnail")[0].getAttribute("url");
} else {
var flurl = items[i].getElementsByTagName("media:thumbnail")[0].getAttribute("url");
};
blob+="<a href='"+flink+"'><img height='75' width='75' src='"+flurl+"' /></a>";
};
blob+="</div>";
$("hyperspace").innerHTML+=blob;
} else {
social.fallBack.flickr();
}
}

As an aside, you can call the method like this, as well:

items[i].getElementsByTagNameNS("*","thumbnail")

That, not surprisingly, searches all namespaces. I’m not sure about the performance hit between the two, but it’s there if you’re too lazy to look up the actual namespace URI and the tag name is sufficiently unique.

One thought on “getElementsByTagNameNS. Now I Know. And Knowing is Half the Battle.

  1. god! IE is sooo annoying! Thanks for the solution. The fix for me (using google feed api) was:

    if ( document.getElementsByTagNameNS !== undefined ) {
    var mediathumb = google.feeds.getElementsByTagNameNS(item,’*’, ‘thumbnail’)[0].getAttribute(“url”);
    } else {
    var mediathumb = item.getElementsByTagName(‘media:thumbnail’)[0].getAttribute(“url”);
    };

Leave a Reply

Your email address will not be published. Required fields are marked *