Home > other >  How to insert an adjacent element if child element contains specific text?
How to insert an adjacent element if child element contains specific text?

Time:11-14

I'm inserting an element with the following code:

var descriptions = document.querySelectorAll(".product-item-info");

function showDescription() {
  descriptions.forEach(description => {
      description.insertAdjacentHTML("beforeend", "<div class='description'>Some text</div>");
   
  });
}

showDescription();

This works well. But how do I check if a child of .product-item-info contains specific text, and if so then not add the markup to said element?

I know how to do this with jQuery.

Edit: change afterend to beforeend

CodePudding user response:

You do it with the DOM the same way you do it with jQuery, it's just you have to do a bit that jQuery does behind the scenes in your own code: Seeing if elements contain that text. There's no real shortcut, you just have to look at the text of the element:

const descriptions = document.querySelectorAll(".product-item-info");

function showDescription() {
    for (const description of descriptions) {
        if (!description.textContent.includes("Some text")) {
            description.insertAdjacentHTML("beforeend", "<div class='description'>Some text</div>");
        }
    }
}

showDescription();

(The optional chaining handles the case where a description doesn't have a next element sibling.)

  • Related