How to add additional attribute to an id in element?

675 views Asked by At

Couldn't find here at Stackoverflow.

How can I add additional attribute to an element?

I need this

<div id="test"></div>

to be

<div id="test test2"></div>

document.getElementById("test").setAttribute("id", "test2") sets to

<div id="test2"></div>

EDIT: the question provided was different question and not about class.

2

There are 2 answers

0
Christos Lytras On BEST ANSWER

Try to read the attribute by using the getAttribute and then con-cat the new value at the end like this:

document.getElementById("test").setAttribute("id", document.getElementById("test").getAttribute("id") + " test2")

EDIT

Just keep in mind to avoid doing this with the ID attribute. You can do it with almost any other attribute though.

Example with the class attribute

document.getElementById("test1").setAttribute("class", document.getElementById("test1").getAttribute("class") + " test2class")
.test {
  color:black;
}

.test.test2class {
  color:red;
}
<div id="test1" class="test">This is a test</div>

0
Dekel On

Well, actually you are not looking to add a new attribute, you are looking for a way to change the value of an attribute that is already exists.

The setAttribute function can do this for you:

document.getElementById("test").setAttribute("id", document.getElementById("test").getAttribute("id") + " test2")

(After running this code you will get id="test test2" on your element).

Note that specifically the id attribute should not contain spaces