InnerHTML getting Div Name
I am trying to get a name of a DIV
<div id="test" name="info1" onclick="func(this.name)">Thi开发者_StackOverflow社区s is div 1</div>
but when I try to print out the name of the div using innerHTML is comes back as undefined. Can this be done or am i doing something wrong?
According to W3Schools a div
cannot have a name
attribute, but it can have an id
, class
or title
. I think the DOM isn't recognising the attribute, therefore not making it available to Javascript.
I made an example here which shows title
working and name
failing as you describe.
Best way to grab an attribute off a node is to use getAttribute as only a small subset of attributes are accessible directly (Title for instance can be, where as alt can't).
The getAttribute() method will also work fine with none standard attributes (which can be pretty useful at times)
The below code should pass it the nodes name to the func function correctly :)
<div id="test" name="info1" onclick="func(this.getAttribute('name')">This is div 1</div>
Hope that helps.
If you want to get the name of the div, you should write some code that can get the attribute from an element (if you're not interested in cross-browser support just use elem.getAttribute)
For example:
var getAttr = function(ele, attr) {
var result = ele.getAttribute(attr) || ele[attr] || null, attrs, len;
if( !result ) {
attrs = ele.attributes;
len = attrs.length;
for(var i = 0; i < len; i++)
if(attrs[i].nodeName === attr)
result = attrs[i].nodeValue;
}
return result;
};
Then you could do
<div id="test" name="info1" onclick="func(getAttr(this, 'name'))">This is div 1</div>
精彩评论