I want to get an element using id:
var a = document.getElementById("hello");
and then dynamically add an attribute to it called "labelText" and assign the value "{labeltext}" to it.
do i need to use concatenation?
i tried the following but it didn't work:
document.getElementById("hello").setAttribute("labelText", "'{' + labelText + '}' ");
I want to get an element using id:
var a = document.getElementById("hello");
and then dynamically add an attribute to it called "labelText" and assign the value "{labeltext}" to it.
do i need to use concatenation?
i tried the following but it didn't work:
document.getElementById("hello").setAttribute("labelText", "'{' + labelText + '}' ");
Share
Improve this question
edited Aug 22, 2016 at 0:39
sarah
asked Aug 22, 2016 at 0:21
sarahsarah
1571 gold badge3 silver badges11 bronze badges
13
- Your quotes are wrong. – SLaks Commented Aug 22, 2016 at 0:22
- can you please give more explanation – sarah Commented Aug 22, 2016 at 0:24
- @SLaks where? can you please correct the code statement – sarah Commented Aug 22, 2016 at 0:26
-
1
"string" + variable + "string"
=>"{" + labelText + "}"
– Ram Commented Aug 22, 2016 at 0:27 -
2
setAttribute
is the correct way of setting an attribute on a DOM element. You need to elaborate on "it didn't work". – Felix Kling Commented Aug 22, 2016 at 0:45
1 Answer
Reset to default 2What you are doing basically works, with the syntax errors first explicitly identified by Vohuman corrected.
//Assign the Attribute:
var labelText='Some Value';
document.getElementById("hello").setAttribute('labelText', '{' + labelText + '}' );
//Define some variables for getting the results
var attributeEl = document.getElementById("attribute");
var theHTMLEl = document.getElementById("theHTML");
///Get the attribute value
var textLabelValue = document.getElementById("hello").getAttribute('labelText');
//Show the results:
attributeEl.textContent = textLabelValue;
theHTMLEl.textContent = document.getElementById("hello").outerHTML;
<div id="hello"></div>
The labelText attribute is:
<div id="attribute"></div>
The resulting HTML is:
<div id="theHTML"></div>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744702180a4588836.html
评论列表(0条)