3

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?

0

3 Answers 3

5

As simple as calling it twice:

var body = document.getElementsByTagName("body")[0];
body.setAttribute("topmargin", "0");
body.setAttribute("leftmargin", "0");
Sign up to request clarification or add additional context in comments.

1 Comment

In this code is ("body") case sensitive? For example will it still apply if the body tag is in caps like <BODY>?
2

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'])

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.