最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Give params to a div created via document.createElement - Stack Overflow

programmeradmin5浏览0评论

I want to create multiple divs using a for loop which i do it like this

for(let i = 0; i < data.length; i++) {
  let divs = document.createElement('div');
  divs.className = 'button';
  divs.data-id = (data[i]).id;                  // error
  document.body.appendChild(divs);
}

Now my issue is that data-id is required but it pops an error. So how can I define data-id dynamically

I also tried giving the whole div as innerHTML of another div but then it wont render. So how can this be solved??

I want to create multiple divs using a for loop which i do it like this

for(let i = 0; i < data.length; i++) {
  let divs = document.createElement('div');
  divs.className = 'button';
  divs.data-id = (data[i]).id;                  // error
  document.body.appendChild(divs);
}

Now my issue is that data-id is required but it pops an error. So how can I define data-id dynamically

I also tried giving the whole div as innerHTML of another div but then it wont render. So how can this be solved??

Share Improve this question asked Mar 16, 2017 at 7:01 iamsakshamiamsaksham 2,9494 gold badges30 silver badges52 bronze badges 1
  • See this: stackoverflow./a/23899918/4964262 – jkythc Commented Mar 16, 2017 at 7:09
Add a ment  | 

4 Answers 4

Reset to default 4

Use setAttribute() instead:

divs.setAttribute('data-id' , data[i].id); 

Also note that hyphens are not allowed in Javascript identifiers, they would be parsed as substraction.

You're looking for divs.setAttribute('data-id', data[i].id);.

If you were trying to read an attribute with a funky character such as that dash in your example, you would access it with brackets instead of dot notation and quote the attribute like so: divs.attributes['data-id']

This should work:

for(let i = 0; i < data.length; i++) {
  let divs = document.createElement('div');
  divs.setAttribute("id", "btn_id");
  divs.setAttribute("class", "btn_class");
  divs.setAttribute("data-id", (data[i]).id);
  document.body.appendChild(divs);
}

Or use Jquery alternatives:

var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})

for(let i = 0; i < data.length; i++) {
  let divs = document.createElement('div');
  var attr = document.createAttribute('data-id');
  attr.value = (data[i]).id;
  divs.setAttributeNode(attr);
  document.body.appendChild(divs);
}
发布评论

评论列表(0)

  1. 暂无评论