Home > other >  Exchange the tags of all elements of a class with JavaScript
Exchange the tags of all elements of a class with JavaScript

Time:12-15

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 >Hi</li>
<li >Hi</li>
<li >Hi</li>
<li >Hi</li>
<li >Hi</li>
<li >Hi</li>
<li >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>)

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

CodePudding user response:

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 >Hi</li>
  <li >Hi</li>
  <li >Hi</li>
  <li >Hi</li>
  <li >Hi</li>
  <li >Hi</li>
  <li >Hi</li>
</ul>

  • Related