简体   繁体   中英

How to pass a html tag inside as variable in javascript?

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.

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

var label = document.createElement('label');
label.innerHTML = floors[flooring];

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM