How to catch div’s son with contains

Asked

Viewed 162 times

0

In that case I want to test the div with class name, but after testing I want the CSS changes to be made in div with class teste.

<div class="teste">
  <div class="name">um nome</div>
  <div class="outradiv">outra coisa</div>
</div>

  $(".text").on('keyup', function (e) 
  {
    $(".teste:contains('"+$(".text").val().toLowerCase()+"')").css("display", "block");
    $(":not(.teste:contains('"+$(".text").val().toLowerCase()+"'))").css("display", "none");
  });

1 answer

2


I think these selectors will scramble the thing. You can make it simpler by checking if the element text contains the string you want.

Example:

$(".text").on('keyup', function(e) {
  var texto = this.value.toLowerCase();
  $(".teste").each(function() {
    var contem = $(this).text().indexOf(texto) > -1;
    $(this).find(".name").css("display", contem ? "block" : "none");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="text">
<div class="teste">
  <div class="name">um nome</div>
  <div class="outradiv">uma coisa</div>
</div>

<div class="teste">
  <div class="name">outro nome</div>
  <div class="outradiv">outra coisa</div>
</div>

To hide .teste when you type anything that’s on .name or .outradiv:

$(".text").on('keyup', function(e) {
  var texto = this.value.toLowerCase();
  $(".teste").each(function() {
    var contem = $(this).text().indexOf(texto) > -1;
    $(this).css("display", contem ? "block" : "none");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="text">
<div class="teste">
  <div class="name">um nome</div>
  <div class="outradiv">uma coisa</div>
</div>

<div class="teste">
  <div class="name">outro nome</div>
  <div class="outradiv">outra coisa</div>
</div>

  • If it is more than one div with the class teste, would work in the same way ??

  • @Lucascarezia in this case may need an adjustment. The input is only 1 or there is an input per .teste?

  • has only one input, and several .teste

  • @Lucascarezia edited the answer to work with N .teste

  • It didn’t work as well as I imagined, I’ll try to explain better, when you type anything that is in .name or .outradiv I want you to share it with the class .teste scram.

  • @Lucascarezia this is even simpler. I will add to the answer.

  • @Lucascarezia in my code (second example) never refer .outradiv logic only takes into account the content of itself .teste. Make a jsFiddle with this example that I can take a look at.

  • I managed to solve the problem, I was just using uppercase letters, thank you.

Show 3 more comments

Browser other questions tagged

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