简体   繁体   中英

How to add element data attribute value inside of the element html

I can`t add data from id attribute to tag I have this:

<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>

I want this:

<div id="id1">id1</div>
<div id="id2">id2</div>
<div id="id3">id3</div>

I wrote this in JS:

let divs = document.getElementsByTagName('div');

for (let div of divs) {
  divs.innerHTML=div.id;
}

But it doesn`t work, please help me.

You are trying to access the innerHTML property of an array ( divs ). You need to access that property of your div object, which is the current div of your loop.

 let divs = document.getElementsByTagName('div'); for (let div of divs) { // you had divs here div.innerHTML=div.id; }
 <div id="id1"></div> <div id="id2"></div> <div id="id3"></div>

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