2017-10-24 4 views
0

Gibt es etwas, das entspricht:
.addToAttribute()
Wie zum vorhandenen Attribut hinzufügen?

Anstatt den gesamten Attributwert zurückzuzusetzen ... fügt den aktuellen Wert:
.setAttribute(), die die attribute etwas wie hinzuzufügt.

Heads up
Das Attribut könnte alles sein: Name, ID, Titel ... etc.
ich jedes Attribut nach Belieben hinzufügen muß und nicht nur auf den class



Was ich habe

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




Was sollte es

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

Antwort

6

anmelden können Sie verwenden:

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

Beispiel:

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

Verwandte Themen