1

Trying to figure out how to do this with pure js so jquery isn't an option.

Say I want to grab all paragraph tags in a div and insert a new div after every paragraph that does not contain a single image or some other criteria.

Assuming I get all paragraphs like:

const paragraphs = document.getElementsByTagName("p");

how can I loop through every paragraph, evaluate if it meets the criteria and append a div if it does? I'm realizing a for loop through every element of the HTMLCollection paragraphs is not an option because HTMLCollections are live.

What is the most efficient way to accomplish this with pure javascript, assuming the newest version of Chrome is used.

b.danigan
  • 33
  • 6

1 Answers1

0

Don't mess with live HTMLCollections, they are a throwback when such things were needed. Use querySelectorAll() because the NodeList it returns is "static".

Details are commented in Snippet

SNIPPET

/* Collect all <p> into a NodeList then convert it into an
|| array
*/
var pArray = Array.from(document.querySelectorAll('p'));

/* Using the .map() method 
|| on every <p> check to see if each one has any text
|| If so, then replace that text with the index number of
|| the <p>. Otherwise black it out and add a <div> after
|| it with the insertAdjacentHTML() method 
*/
pArray.map(function(txt, idx) {
  if (txt.textContent.length > 0) {
    txt.textContent = idx;
  } else {
    txt.style.background = 'black';
    txt.insertAdjacentHTML('afterend', '<div></div>');
  }
});
p {
  border: 1px solid red;
  font: 10px/1 Arial;
  height: 10px;
}

div {
  background: red;
  height: 10px;
}
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p></p>
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p>TEXT</p>
<p>TEXT</p>
<p></p>
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p>TEXT</p>
<p></p>
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p></p>
<p>TEXT</p>
<p>TEXT</p>
zer00ne
  • 41,936
  • 6
  • 41
  • 68