jquery - Insert multiple attributes into html tag using JavaScript and not between tags - Stack Overflow

From a previous quest we asked about inserting a new attribute into a html tag and the code below does

From a previous quest we asked about inserting a new attribute into a html tag and the code below does the job nicely, but how should it be coded to add multiple attributes, for example changing..

<body bgcolor="#DDDDDD">

to...

<body bgcolor="#DDDDDD" topmargin="0" leftmargin="0"> 

The code that works for a single attribute is...

document.getElementsByTagName("body")[0].setAttribute("id", "something");

How to modify this for inserting multiple attributes?

From a previous quest we asked about inserting a new attribute into a html tag and the code below does the job nicely, but how should it be coded to add multiple attributes, for example changing..

<body bgcolor="#DDDDDD">

to...

<body bgcolor="#DDDDDD" topmargin="0" leftmargin="0"> 

The code that works for a single attribute is...

document.getElementsByTagName("body")[0].setAttribute("id", "something");

How to modify this for inserting multiple attributes?

Share Improve this question edited Dec 6, 2012 at 5:07 Akhil Sekharan 12.7k8 gold badges42 silver badges58 bronze badges asked Dec 6, 2012 at 4:49 WilliamKWilliamK 7982 gold badges14 silver badges32 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

As simple as calling it twice:

var body = document.getElementsByTagName("body")[0];
body.setAttribute("topmargin", "0");
body.setAttribute("leftmargin", "0");

Using jQuery:

$('body').attr({
  topmargin: 0,
  leftmargin: 0
});

Using JS:

Write a function yourself like:

    HTMLElement.prototype.setAttributes= function(attrs, values) {
        for(var i=0;i<attrs.length;i++){
            this.setAttribute(attrs[i] ,+values[i]);
        }
    };

    //And call it like:

    document.getElementById('custom-header').setAttributes(['topmargin','leftmargin'],['0','0'])

May By like this

document.getElementsByTagName("body")[0].setAttribute("id", "something");
document.getElementsByTagName("body")[0].setAttribute("topmargin", "0");
document.getElementsByTagName("body")[0].setAttribute("leftmargin", "0");

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745271686a4619786.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信