admin管理员组文章数量:1391995
I have the following
<body class="test test1 test2" style="color:red; font-size:12px">...</body>
Using jQuery, How can i store all attributes of the body tag in variable x. So in other words i want
var x = 'class="test test1 test2" style="color:red; font-size:12px"';
I have the following
<body class="test test1 test2" style="color:red; font-size:12px">...</body>
Using jQuery, How can i store all attributes of the body tag in variable x. So in other words i want
var x = 'class="test test1 test2" style="color:red; font-size:12px"';
3 Answers
Reset to default 4You can use element.attributes
something like:
var body = document.body,
attries = body.attributes,
arr = [];
for(var i=0, len=attries.length; i<len; i++){
var attr = attries[i];
arr.push(attr.nodeName + '="' + attr.nodeValue + '"');
}
var x = arr.join(" ");
alert(x);
See it here: http://jsbin./ihiwod
UPDATE:
However, in IE(<=7), the code above would generate more attributes than you want because attributes that are not set are also added to element.attributes
in those browsers.
the improved code is:
var body = document.body,
attries = body.attributes,
arr = [];
for(var i=0, len=attries.length; i<len; i++){
var attr = attries[i];
if(attr.specified){
var attr_name = attr.nodeName,
attr_val = attr_name === "style" ? body.style.cssText
: attr.nodeValue;
arr.push(attr_name + '="' + attr_val + '"');
}
}
var x = arr.join(" ");
alert(x);
var attrs = document.body.attributes;
var attributes = [];
for(var i=0; i<attrs.length; i++) {
attributes.push(attrs[i].nodeName + '="' + attrs[i].nodeValue + '"');
}
var x = attributes.join(" ")
As far as I know, jQuery can't do this by itself, but there is a plugin available: http://plugins.jquery./project/getAttributes. You might want to check that out.
本文标签: javascriptHow to get all class and style attributes of body tag in one variableStack Overflow
版权声明:本文标题:javascript - How to get all class and style attributes of body tag in one variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744682519a2619497.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论