JavaScript DOM document function to add ‘for’ attribute to a html tag

I have following working code in HTML and JS:

HTML:

<label class="slider-text" for="masterChannel">

JS:

const masterChannel = document.querySelector('#masterChannel');
//Do more stuff...

now my plan is to convert my entire html code to JavaScript and so far, I have this:

  var label = document.createElement("label");
  label.classList.add("slider-text");
  //here I need to add the 'for' attribute to 'label' tag

I was not able to find any method in JS to add for attribute to a tag and I am not sure if I can achieve the same result with a different approach.

Answer

I was not able to find any method in JS to add for attribute to a tag

Searching Google for “add attribute to tag with javascript” yields several correct answers, the 1st being setAttribute().

var label = document.createElement("label");
label.classList.add("slider-text");
label.setAttribute("for", "masterChannel");

console.log(label);

Additionally, as @Pointy mentioned, you can also use the .htmlFor DOM property on the object:

var label = document.createElement("label");
label.classList.add("slider-text");
label.htmlFor = "masterChannel";

console.log(label);

And, by the way, the code in your question of:

const masterChannel = document.querySelector('#masterChannel');

would not get a reference to the label you showed with this HTML:

<label class="slider-text" for="masterChannel">

because # in .querySelector() refers to the id of an element and you have no id in your label element’s code. For the HTML you showed, you could use:

const masterChannel = document.querySelector("[for='masterChannel']");

because [] represent the attribute selector in CSS.

Leave a Reply

Your email address will not be published. Required fields are marked *