Detect word within an element that is within a specific class

Asked

Viewed 51 times

1

I have the following code. I tried to run inside the element with the ACTIVE class, a code that checked if it had the word VIOLET inside the element with the class TITLE. But instead of running only on the element with the ACTIVE class, it ran on everyone with the VIOLET word:

var Violet = /Violet/gi;

$('.title').append($('div').hasClass("active")).contents().each(function() {
  if (this.nodeType === 3 && this.nodeValue.match(Violet)) {
    alert('teste')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="owl-1">
  <div class="owl-item active">
    <li>
      <div class="title">Violet</div>
    </li>
  </div>
  <div class="owl-item">
    <li>
      <div class="title">Violet</div>
    </li>
  </div>
  <div class="owl-item">
    <li>
      <div class="title">Evergarden</div>
    </li>
  </div>
</ul>

2 answers

0

Probably the following code can solve the problem:

var Violet = /Violet/gi;

if($("div.active .title").text().match(/Violet/gi)){
    alert('teste')
}

The $("div.active .title") selector searches for the element with the title class within a div element with the active class. The result will be an array if you find a value or null/Undefined if there is no element matching that query.

-1

Thank you very much Leandrade and Samuelf. With the help of you 2, I managed to make a code that meets my needs.

var violet = /Violet/gi;
 $('div.active').find('li').find('div.title').contents().each(function() {
  if(this.nodeType === 3 && this.nodeValue.match(violet)) {
  $('div.active').find('li').find('div.title').css('color','red');      
  } else{
    alert('Erro. O texto não é este!'); }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="owl-1">
  <div class="owl-item active">
    <li>
      <div class="title">Violet</div>
    </li>
  </div>
  <div class="owl-item">
    <li>
      <div class="title">Violet</div>
    </li>
  </div>
  <div class="owl-item">
    <li>
      <div class="title">Evergarden</div>
    </li>
  </div>
</ul>

  • Use two find is redundant: $('div.active').find('li').find('div.title').css('color','red'); ... would suffice $('div.active div.title').css('color','red');... see that you don’t even need .find()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.