Check that there is a word on a div and then change its class

3

Suppose I have a div with a string of characters and I want to see if there is a specific word and do something:

$('.container-text:contains("text")').addClass('container-text-right');

But how do I check if I want him to check more than one word and then do something according to a certain condition? for example ...

if($('.container-text:contains("texto1")')){
  $('.container-text').addClass('container-text-right');
   // y hacer algo más
} else if ($('.container-text:contains("texto2")')){
  $('.container-text').addClass('container-text-right');
  // y hacer algo más
}

This is how I want to check it but I do not give with it, what do you say to me?

    
asked by djohny 03.10.2016 в 17:42
source

2 answers

2

I do not understand your idea very well, but what you want to do, you can do it by checking the length of the chain you are looking for:

if($(".container-text:contains('Hola')").length > 0){
  $( ".container-text:contains('Hola')" ).addClass("cambio1");
}

if($(".container-text:contains('Mundo')").length > 0){
  $( ".container-text:contains('Mundo')" ).addClass("cambio");
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Contains</title>
</head>
<body>
  <style>
    .cambio{
      color:#0f0;
    }
    .cambio1{
      text-decoration:underline;
    }
  </style>
  <div class="container-text">Hola</div>
  <div class="container-text">Mundo</div>
  <div class="container-text">Mundo!</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
    
answered by 03.10.2016 / 18:28
source
2

concatenate the contains in the following way

/* , el operador , funciona como un or */
$("div:contains('texto1'), div:contains('texto2'), div:contains('texto3')")
/* la concatenación como el AND */
$("div:contains('texto1'):contains('texto2'):contains('texto3')")

The final code would remain that way, taking into account that instead of css it would be addClass

$(".field:contains('Hola'):contains('Mundo')").css('background', 'yellow');
<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <title>Contains</title>
</head>
<body>

<div class="field"> 
   Hola Mundo
</div>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
 </body>
 </html>
    
answered by 03.10.2016 в 18:37