jQuery Insert set of attributes as string to tag
I have variable x that contains set of attributes.
var x = 'class="test test1 test2" id="xyz" style="color:red"';
How can i insert x to the <body>
tag. so body looks like
<body class="test test1 test2" i开发者_运维百科d="xyz" style="color:red">
you could create a temp element and att attributes to it and then append all of its attributes to the body:
var x = 'class="test test1 test2" id="xyz" style="color:red"',
temp = $("<b "+x+">")[0],
attr = {};
for (var i=0, attrs=temp.attributes, l=attrs.length; i<l; i++){
attr[attrs.item(i).nodeName] = attrs.item(i).value;
}
$("body").attr(attr);
demo: http://jsbin.com/udilib/edit#javascript,html,live
but if you can then make the class, id and style as an object instead of a string, will save some code for you.
This probably isn't bullet-proof, but it seems to handle your example input fine:
var x = 'class="test test1 test2" id="xyz" style="color:red"',
pairs = x.match(/\w+\=\"[^\"]+\"/g),
$body = $('body');
for (var i = 0, len = pairs.length; i < len; i++) {
var parts = pairs[i].split('='),
attrName = parts[0],
attrValue = parts[1].replace(/\"/g, '');
$body.attr(attrName, attrValue);
}
精彩评论