-1

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.

A.I.
  • 37
  • 7
  • Does this answer your question? [Append custom attributes to a DOM node](https://stackoverflow.com/questions/3363463/append-custom-attributes-to-a-dom-node) – luk2302 Apr 01 '21 at 17:32
  • You haven't found `.setAttribute()`? You haven't tried `label.for = ...`? – Andreas Apr 01 '21 at 17:32
  • Ah sorry, it'd be `label.htmlFor = "masterChannel";` – Pointy Apr 01 '21 at 17:38
  • @Pointy I tired label.htmlFor but was not able to make my code work, but I think it's my mistake since Scott-Marcus pointed out my querySelector is not correct. Thank you for the feedback. – A.I. Apr 01 '21 at 17:51

1 Answers1

1

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.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71