skip to Main Content

Hi have a working JS function to add a div based on text inside an element, se below. In the example for something like

<div class="class">sometext</div>

This works well, but how do I make it for this exact match only, so it wont add the extra div if the element has another word (Which I know what it is)

Example where I dont want it to add the div:

<div class="class">sometext remove</div>

const descriptions = document.querySelectorAll(".class");
function showDescription() {
    for (const description of descriptions) {
        
        if (description.textContent.includes("sometext")) {
            description.insertAdjacentHTML("beforeend", "<div></div>");
        }
    }
}
showDescription();

2

Answers


  1. ou can use Regex for that :

    const str = 'sometext';
    const regex = /^word$/;
    const containsSometext = regex.test(str);
    

    here the ^ refers to the start of the string and $ refers to the end of it
    containsSometext will return true if the est is true and false if not

    Login or Signup to reply.
  2. You can simple use === like:

    const descriptions = document.querySelectorAll(".class");
    function showDescription() {
        for (const description of descriptions) {
            
            if (description.textContent === "sometext") {
                description.insertAdjacentHTML("beforeend", "<div>newDiv</div>");
            }
        }
    }
    showDescription();
    <div class="class">sometext</div>
    <div class="class">sometext2</div>
    <div class="class">sometext</div>
    <div class="class">sometext remove</div>

    If you have two words you can use || with === or an array like:

    1:

    const descriptions = document.querySelectorAll(".class");
    function showDescription() {
        for (const description of descriptions) {
            
            if (description.textContent === "sometext" || description.textContent === "sometext2") {
                description.insertAdjacentHTML("beforeend", "<div>newDiv</div>");
            }
        }
    }
    showDescription();
    <div class="class">sometext</div>
    <div class="class">sometext2</div>
    <div class="class">sometext</div>
    <div class="class">sometext remove</div>

    2:

    const descriptions = document.querySelectorAll(".class");
    const textForDiv = ['sometext','sometext2'];
    function showDescription() {
        for (const description of descriptions) {
            textForDiv.forEach(el => {
              if (description.textContent === el) {
                description.insertAdjacentHTML("beforeend", "<div>newDiv</div>");
            }
            });        
        }
    }
    showDescription();
    <div class="class">sometext</div>
    <div class="class">sometext2</div>
    <div class="class">sometext</div>
    <div class="class">sometext remove</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search