简体   繁体   中英

Creates element to the HTML DOM

This is my script

var item = document.createElement('LI');
var title = document.createElement('A');
title.href = '#';
title.className = 'service-tag';
title.innerHTML = titleText;
item.appendChild(title);
panel.appendChild(item);

Script above will create html code like this

 <li><a href="#" class="service-tag">Some title</a></li>

with titleText is Some title

So I want create below html code like

<li data-genre="Some title"><a href="#" class="service-tag">Some title</a></li>

How can I add data-genre="Some title" into <li> like html code above?

You need to use setAttribute

item.setAttribute("data-genre", "Some title");

 var panel = document.createElement('UL'); var titleText = "some title"; var item = document.createElement('LI'); item.setAttribute("data-genre", "Some title"); var title = document.createElement('A'); title.href = '#'; title.className = 'service-tag'; title.innerHTML = titleText; item.appendChild(title); panel.appendChild(item); document.body.appendChild(panel); 

Try this,

  var titleText = "something"; var panel = document.getElementById('panel'); var item = document.createElement('LI'); att = document.createAttribute("data-genre"); att.value = "some"; item.setAttributeNode(att); var title = document.createElement('A'); title.href = '#'; title.className = 'service-tag'; title.innerHTML = titleText; item.appendChild(title); panel.appendChild(item); 

You can try this one.

var item = document.createElement('LI');
var title = document.createElement('A');
title.setAttribute('data-genre', 'Some title')
title.href = '#';
title.className = 'service-tag';
title.innerHTML = titleText;
item.appendChild(title);
panel.appendChild(item);

What you missed is, setAttribute . You can set any attribute using this.

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