Pinkie
Pinkie

Reputation: 10256

How to get all class and style attributes of body tag in one variable

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

Upvotes: 0

Views: 4495

Answers (3)

wong2
wong2

Reputation: 35730

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.com/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);

Upvotes: 4

Rob W
Rob W

Reputation: 349032

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(" ")

Upvotes: 3

Peter
Peter

Reputation: 14108

As far as I know, jQuery can't do this by itself, but there is a plugin available: http://plugins.jquery.com/project/getAttributes. You might want to check that out.

Upvotes: 0

Related Questions