Home > Software design >  Add Class to div when a specific word appears a specific number of times on page
Add Class to div when a specific word appears a specific number of times on page

Time:06-11

So, my aim is to add a Class name to a div but only when the word "premium" appears 10 times on the page.

My current code below adds a Class whenever the word "premium" appears. However, I need the Class name to only be added after 10 instances of the word.

.listing-package is the div where the word "premium" occurs and .submit-post is the div that I need to add a Class name to.

Any help would be greatly appreciated! Cheers :)

$(document).ready(function() {   
    document.querySelectorAll('.listing-package').forEach(el=>
    {
        if (/premium/.test(el.textContent) )
        { document.querySelector(".submit-post").classList.add("disabled") } 
    })
})

CodePudding user response:

document.querySelectorAll gives a list of elements that contain a certain tag like a class or an id. Maybe you could use its length to know if it has 10 (or more) elements.

CodePudding user response:

Change premium word check in if condition.

if (el.textContent.match(/premium/g) || []).length >= 10)
  • Related