Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript window.onload change text of each id by targeting

I have this code and want to change text of each id when window loaded by targeting

function change_text() {
  const incList = document.querySelectorAll("[id ^=\'inc_\']");
  [].forEach.call(incList, function() {
    const tID = this.getAttribute("target");
    document.getElementById("inc_" + tID).innerText += tID;
  });
}
window.onload = change_text;
<div id="inc_1" target="1">111</div>
<div id="inc_2" target="2">222</div>
<div id="inc_3" target="3">333</div>
<div id="inc_4" target="4">444</div>
<div id="inc_5" target="5">555</div>

But it doesn’t work. Help, please!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First, this isn’t bind on callback function in forEach.

You just need to put the parameter in callback function in forEach

function change_text() {
  const incList = document.querySelectorAll("[id ^=\'inc_\']");
  [].forEach.call(incList, function(element) {
    const tID = element.getAttribute("target");
    document.getElementById("inc_" + tID).innerText += tID;
  });
}
window.onload = change_text;
<div id="inc_1" target="1">111</div>
<div id="inc_2" target="2">222</div>
<div id="inc_3" target="3">333</div>
<div id="inc_4" target="4">444</div>
<div id="inc_5" target="5">555</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading