Home > Enterprise >  Replace a bunch of elements
Replace a bunch of elements

Time:12-09

I am trying to replace a bunch of divs with javascript.

const ref_link = document.querySelectorAll('.is-field.link');

ref_link.forEach(function (element) {

    const ref_link_content = element.querySelector(".is-field.link .value").innerHTML;
    alert(ref_link_content);

    const ref_link_new = document.createElement('a');
    
    ref_link_new.innerHTML = '<p ><a href="'   ref_link_content   '">Website</a></p>';
    ref_link.parentNode.replaceChild(ref_link_new, ref_link);
});
<div >
  <div >https://link1.com</div>
</div>

<div >
  <div >https://link2.com</div>
</div>

<div >
  <div >https://link3.com</div>
</div>

This alerts the first content just fine. But afterwards generates an error message in the console:

header.js?ver=1.0:35 
        
       Uncaught TypeError: Cannot read properties of undefined (reading 'replaceChild')
    at header.js?ver=1.0:35:21
    at NodeList.forEach (<anonymous>)
    at header.js?ver=1.0:27:10

The result should look like the following

    <div >
      <p ><a href="https://link1.com">Website</a></p>
    </div>

    <div >
      <p ><a href="https://link2.com">Website</a></p>
    </div>

    <div >
      <p ><a href="https://link3.com">Website</a></p>
    </div>

What am I doing wrong?

CodePudding user response:

When you do this.parentNode.replaceChild(ref_link_new, ref_link);, you are trying to use window and the live html collection. You are not using the element you are referencing.

It should be element.parentNode.replaceChild(ref_link_new, element);

You have a bunch of other issues like you are trying to select an element using the selector of the element you have and you are making invalid html with an anchor in an anchor.

Code should just be selecting the divs that have the links and replacing them with the p and a tag. replaceWith is easier to use.

const ref_links = document.querySelectorAll('.is-field.link .value');

ref_links.forEach(function (element) {

    const ref_link_new = document.createElement('p');
    ref_link_new.classList.add('icon');  
    
    ref_link_new.innerHTML = '<a href="'   element.textContent   '">Website</a>';
    
    element.replaceWith(ref_link_new);
});
.icon::before { 
  content: '\1F517'; 
  color: green;
}
<div >
  <div >https://link1.com</div>
</div>

<div >
  <div >https://link2.com</div>
</div>

<div >
  <div >https://link3.com</div>
</div>

CodePudding user response:

Thank you all, I got it :)

const ref_link = document.querySelectorAll('.is-field.link');

ref_link.forEach(function (element) {

const ref_link_content = element.querySelector(".value").innerHTML;
const ref_link_new = document.createElement('p');
ref_link_new.classList.add('icon');

ref_link_new.innerHTML = '<a href="'   ref_link_content   '">Website</a>';
element.parentNode.replaceChild(ref_link_new, element);
});

  • Related