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

Exchange the tags of all elements of a class with JavaScript

var f = document.querySelector('.example');
var g = document.createElement('h2');
for (let i = 0; i < f.length; i++) {
    g.innerHTML = f[i].innerHTML;
    f[i].parentNode.replaceChild(g, f[i]);
}
<ul>
<li class="example">Hi</li>
<li class="example">Hi</li>
<li class="example">Hi</li>
<li class="example">Hi</li>
<li class="example">Hi</li>
<li class="example">Hi</li>
<li class="example">Hi</li>
</ul>

here is what I would like to do:

I want to make accessibility adjustments to a WordPress theme with JavaScript afterwards.

In the following case i want to overwrite all element-tags of the class ".example" with the tag <h2> (currently they are <div>)

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

With the code example here I only reach the first element (I know that), but i want to "overwrite" all of them with the new tag:

var f = document.querySelector('.example');
var g = document.createElement('h2');
g.innerHTML = f.innerHTML;
f.parentNode.replaceChild(g, f);

How do i do that, i have already tried something like:

var f = document.querySelector('.example');
var g = document.createElement('h2');
for (let i = 0; i < f.length; i++) {
    g.innerHTML = f[i].innerHTML;
    f[i].parentNode.replaceChild(g, f);
}

But it doesn’t work. I think that should be simple, but I am a newbie.

Thank you 🙂

>Solution :

You need to create a new <h2> element each time through the loop, not reuse the same element g. And you need to use document.querySelectorAll() to get all the .example elements so you can loop over them.

var f = document.querySelectorAll('.example');
for (let i = 0; i < f.length; i++) {
  var g = document.createElement('h2');
  g.innerHTML = f[i].innerHTML;
  f[i].parentNode.replaceChild(g, f[i]);
}
<ul>
  <li class="example">Hi</li>
  <li class="example">Hi</li>
  <li class="example">Hi</li>
  <li class="example">Hi</li>
  <li class="example">Hi</li>
  <li class="example">Hi</li>
  <li class="example">Hi</li>
</ul>
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