I’m trying to parse Reddit’s XML file with javascript and im having trouble retrieving an attribute from a node with a namespace. I want to get the following URL
<media:thumbnail url="http://f.thumbs.redditmedia.com/LdOsi1MnWuzGvbDq.jpg"/>
What I tried so far but none of these have worked:
<script type="text/javascript">
//...XMLHttpRequest...
var items = data.getElementsByTagName("item");
for (var i = 0; i < items.length; i++) {
var item = items[i];
//titleNode and title work fine
var titleNode = item.getElementsByTagName("title")[0];
var title = titleNode.firstChild.data;
//the following don't work, they actually cause the google chrome extension to stop working :(
//attempt 1
thumbnail = item.getElementsByTagName('thumbnail')[0];
//attempt 2
thumbnail = item.getElementsByTagName('media:thumbnail')[0];
//attempt 3
thumbnail = item.getElementsByTagName('media', 'thumbnail')[0];
//attempt 4
thumbnail = item.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0];
//attempt 5
thumbnail = item.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0].getAttriubte("url");
//attempt 6
thumbnail = item.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0].firstChild.data;
document.write(thumbnail);
}
</script>
I’m lost can you offer any help?
worked for me =) [In Chrome] Though I should note that on the particular XML file you referenced, the first few items do not contain
<media:thumbnail>tags.You should check the length of the result of the call to
getElementsByTagNameBEFORE trying to pull out the nth (or in your case the 0th) element, as that will cause an error.e.g.