Jeff S
Jeff S

Reputation: 109

Javascript Loop: inserting element only working on last iteration

I'm working in Wordpress and trying to add an excerpt to each portfolio card in a grid (there's no way for me to do this via the theme.

Here is the custom script that I am using. Everything works as expected, except that only the last node in the list gets the excerpt. I've changed the number of iterations around to test this and it always just inserts the excerpt on the last node that it iterates through.

Based on this it appears that each new iteration undoes or erases what the prior one did.

window.onload = function() {
    const targets = document.querySelectorAll('.entry-header');
    const parent = document.createElement('div');
    const child = document.createElement('p');
    const excerpt = 'This will be the excerpt...';
    
    parent.className = "entry-excerpt";
    parent.appendChild(child);
    child.innerHTML = excerpt;
    
    for (let i = 0; i < targets.length; i++) {
      targets[i].after(parent);
    }
    
  };

I logged targets[i] and each iteration prints correctly

Upvotes: 0

Views: 365

Answers (2)

kgello
kgello

Reputation: 143

You only have one parent element, which visits your entry-headers on the page.

You should try putting everything in the loop. As I assume the excerpts will be different for each entry, you should create a method to generate them dynamically or fetch them from somewhere.

const targets = document.querySelectorAll('.entry-header');
window.onload = function() {
    for (let i = 0; i < targets.length; i++) {
        parent = getExcerpt(i);              
        targets[i].after(parent);
    }
};

function getExcerpt(index) {
    const parent = document.createElement('div');
    const child = document.createElement('p');
    const excerpt = 'This will be the excerpt...';

    parent.className = "entry-excerpt";
    parent.appendChild(child);
    child.innerHTML = excerpt;

    return parent;
}

Upvotes: 2

Kumar
Kumar

Reputation: 3126

Please put the parent inside the loop. Checkout the below example

const targets = document.querySelectorAll('.entry-header');
for (let i = 0; i < targets.length; i++) {
  const parent = document.createElement('div');
  const child = document.createElement('p');
  const excerpt = 'This will be the excerpt...';

  parent.className = "entry-excerpt";
  parent.appendChild(child);
  child.innerHTML = excerpt;
  targets[i].after(parent);
}
<div class="entry-header">Entry Header 1</div>
<div class="entry-header">Entry Header 2</div>
<div class="entry-header">Entry Header 3</div>

Upvotes: 1

Related Questions