Solution 1 :

b.includes("Verhuurd"); document.querySelector(".nf-form-cont").classList.add("displaynone");

You are just adding the class in any case here, you did not make this dependent on any condition.

This should be something like

if( b.includes("Verhuurd") ) { document.querySelector(".nf-form-cont").classList.add("displaynone"); }

Solution 2 :

Your includes() is probably matching “huur” and therefore including divs that contain “Te huur” as well as the ones you’re looking for. Consider making it more specific with another condition to exclude divs that you don’t want.

window.addEventListener("load", () => {
    let b = document.getElementsByClassName('aw-property-data-item')[0].innerHTML;

    if (b.includes("Verhuurd") && !b.includes("Te")) {
        document.querySelector(".nf-form-cont").classList.add("displaynone");
    }
});

Problem :

How can I add a class to a div when another div on the same page contains a specific word?

My html is:

window.addEventListener("load", () => { let b = document.getElementsByClassName('aw-property-data-item')[0].innerHTML; b.includes("Verhuurd"); document.querySelector(".nf-form-cont").classList.add("displaynone"); });
<div class="aw-property-data-item">
<p><strong>Status:</strong>  Verhuurd</p>
</div>

<div id="nf-form-7-cont" class="nf-form-cont">
form content goes here
</div>

This works, the class displaynone is added.

On objects that contain “Te Huur” rather than “Verhuurd” the class displaynone is also added. This should not be the case, but I can’t figure out why this is happening. Any advice is very much appreciated!

Comments

Comment posted by ErwinV

Adding the condition helped. And I also needed to call the correct div, my code did not iterate all the divs with the same class. Thanks for pointing me in the right direction!

Comment posted by ErwinV

This causes the class displaynone to not be added when aw-property-data-item contains Verhuurd as well as when it contains Te Huur.

Comment posted by CBroe

How would

By