0

I am passing an array called floors into a function which creates a html node.

var floors = ["Ground", "First", "Second", "Third", "Duplex", "Duplex+1", "Duplex+2"];
document.createTextNode(" " + floors[flooring]);

Is there anyway to add a html tag to each of these variables. I have tried the below code, but it does not seem to work.

var floors = ["<label>Ground</label>", "<label>First</label>"], AND

document.createTextNode('<label> + floors[flooring] +'</label>');

Is there anyway possible to add html tags to these variable in javascript. Please help.

4
  • What is flooring? Commented Apr 3, 2021 at 7:28
  • 1
    TextNodes contain text, not HTML. But you can do var el = document.createElement('label'); el.innerHTML = floors[flooring]; (assuming flooring is a numeric index) Commented Apr 3, 2021 at 7:30
  • insertAdjacentHTML might be of use Commented Apr 3, 2021 at 7:33
  • flooring is numeric index Commented Apr 3, 2021 at 7:37

2 Answers 2

1

Instead of createTextNode(), use createElement() and set its innerHTML:

var label = document.createElement('label');
label.innerHTML = floors[flooring];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this was simple and worked best.
0

You can do this using innerHTML.

const elements = [
  "<h1>First</h1>",
  "<h1>Second</h1>",
  "<h1>Third</h1>",
  "<h1>Fourth</h1>"
]

for (let el of elements) {
  document.body.innerHTML += el
}

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.