如何添加到现有属性?

时间:2017-10-24 11:40:15

标签: javascript

是否有相当于的东西: .setAttribute()增加了attribute之类的内容:
.addToAttribute()

不是重置整个属性值......而是添加到当前值。

抬头
属性可以是任何内容:name,id,title ...等 我需要随意添加任何属性,而不仅仅是class



我拥有什么

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%;
}




应记录的内容

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 个答案:

答案 0 :(得分:6)

您可以使用:

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

示例:

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%;
}