最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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>

发布评论

评论列表(0)

  1. 暂无评论