1

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?

0

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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.

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.