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 + '}' ");
13
  • Your quotes are wrong. Commented Aug 22, 2016 at 0:22
  • can you please give more explanation Commented Aug 22, 2016 at 0:24
  • @SLaks where? can you please correct the code statement Commented Aug 22, 2016 at 0:26
  • 1
    "string" + variable + "string" => "{" + labelText + "}" 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". Commented Aug 22, 2016 at 0:45

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.