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"';

Share Improve this question edited Sep 13, 2011 at 7:56 wong2 35.8k51 gold badges137 silver badges182 bronze badges asked Sep 13, 2011 at 7:54 PinkiePinkie 10.2k22 gold badges81 silver badges124 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You 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