0

Is there something equivalent to:
.setAttribute() that adds to the attribute something like:
.addToAttribute()

Instead of resetting the entire attribute value… it adds to the current value.

Heads up
The attribute could be anything: name, id, title… etc.
I need to add to any attribute at will and not just to the class



What I have

function one() {
body = document.body
div = document.createElement('div')
body.appendChild(div)
div.setAttribute("class", "blue")
div.setAttribute("name", "John")
div.setAttribute("id", "box")
}
one()



//should be
//name="John new value"
div.setAttribute("name", "new value")
// Is there something equivalent to .setAttribute()?
// Like .addToAttribue()?



console.log(document.getElementById('box'))
.blue {
  width: 100px;
  height: 100px;
  background: red;
  background: blue;
}
[name~="value"] {
border-radius: 50%;
}




What it should log

function one() {
body = document.body
div = document.createElement('div')
body.appendChild(div)
div.setAttribute("class", "blue")
div.setAttribute("name", "name")
div.setAttribute("id", "box")
}
one()



div.setAttribute("name", "John new value")
console.log(document.getElementById('box'))
.blue {
  width: 100px;
  height: 100px;
  background: red;
  background: blue;
}
[name~="value"] {
border-radius: 50%;
}

1 Answer 1

6

You can use:

function addToAttribute(element, attributeName, value) {
    element.setAttribute(
        attributeName, 
        (element.getAttribute(attributeName) || '') + value);
}

Example:

function addToAttribute(element, attributeName, value) {
  element.setAttribute(
attributeName, 
(element.getAttribute(attributeName) || '') + value);
}

function one() {
  var body = document.body
  var div = document.createElement('div')
  body.appendChild(div)
  div.setAttribute("class", "blue")
  div.setAttribute("name", "name")
  div.setAttribute("id", "box")
}
one()

var div = document.getElementById('box');
addToAttribute(div, "name", "John new value")
console.log(div);
.blue {
  width: 100px;
  height: 100px;
  background: red;
  background: blue;
}
[name~="value"] {
border-radius: 50%;
}

Sign up to request clarification or add additional context in comments.

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.