-4

How do I append an class to a specific element which includes a certain text like this:

var title = $('.pass-item .title').text();

if(title.includes('7 days within 1')){
   // Here I want to select the element which has the title text '7 days within 1' 
   // And append a class to it
}

I'll hope someone can help me out :)

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Sireini
  • 4,142
  • 12
  • 52
  • 91

3 Answers3

2

You can search for just that element, using jQuery's :contains, then use addClass to add the class:

$(".pass-item .title:contains('7 days within 1')").addClass("the-class");

If none are found, that's fine, jQuery's API is set-based, so it won't be an error.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You need to first get an array of all the item, them map over that array and check each item for the text it contains. If it has the required text you return it with the new class else just return the item as it

let titles = document.querySelectorAll('.pass-item.title')

titles = Array.prototype.slice.call(titles);

titles.map((item) => { 
    if (item.textContent.includes('7 days within 1')) {
        item.classList.add('new-class')
        return item
    } else {
        return item
    }
});

https://codepen.io/anon/pen/yEQjZw?editors=1111

Jason McFarlane
  • 2,048
  • 3
  • 18
  • 30
  • Just FYI: Using `map` when you aren't using the array it produces isn't best practice; just use `forEach`. Also note that on modern browsers, the NodeList from `querySelectorAll` has `forEach`, so no need for the `slice` (and it's trivial to polyfill if needed). There's also a big difference between `.pass-item .title` (in the question) and `.pass-item.title` (in the answer above). Finally, note the OP is using jQuery, which makes this a one-liner. – T.J. Crowder Jun 28 '18 at 15:17
0

You can however go through every element that has certain classes or attributes and check if they contain the text like this:

$('.title').each(function(){
 if(this.text() == "yabadabadoooo")
 {
  this.addClass("make-me-pretty");
 }
})
Olaf
  • 1,038
  • 8
  • 20