jquery - How to add an attribute dynamically using javascript - Stack Overflow

I want to get an element using id:var a = document.getElementById("hello");and then dynamical

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
 |  Show 8 more ments

1 Answer 1

Reset to default 2

What 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信