Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-browser, javascript getAttribute() method?

Tags:

javascript

trying to determine a decent, cross browser method for obtaining attributes with javascript? assume javascript library use (jQuery/Mootools/etc.) is not an option.

I've tried the following, but I frequently get "attributes" is null or not an object error when IE tries to use the "else" method. Can anyone assist?

<script type="text/javascript">
//...
    getAttr: function(ele, attr) {
      if (typeof ele.attributes[attr] == 'undefined'){
        return ele.getAttribute(attr);
      } else {
        return ele.attributes[attr].nodeValue;
      }
    },
//...
</script>


<div>
 <a href="http://www.yo.com#foo">Link</a>
</div>

using the above html, in each browser, how do I getAttr(ele, 'href')? (assume selecting the ele node isn't an issue)

like image 748
tester Avatar asked Sep 20 '10 20:09

tester


1 Answers

For the vast majority of cases you can simply use the built in getAttribute function.

e.g.

ele.getAttribute(attr)

According to QuirksMode this should work on all major browsers (IE >= 6 included), with a minor exception:

In IE5-7, accessing the style attribute gives an object, and accessing the onclick attribute gives an anonymous function wrapped around the actual content.

like image 92
Mark Rhodes Avatar answered Sep 26 '22 02:09

Mark Rhodes