Ibrahim Yousry
Ibrahim Yousry

Reputation: 59

checking if element's text is same as another element's text

I'm trying to do is when I click on a text, if another div has a child that contains this text fade in. but it's not working

$('.rel-head').click(function() {

  if ($('.art-h .head-art'): contains($(this).text())) {
    $(this).parent().fadeIn().siblings().fadeOut();
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="art-h">
  <div class="head-art">some text</div>
</div>
<div class="art-h">
  <div class="head-art">anoter text</div>
</div>
<div class "related-heads">
  <h1 class="rel-head">some text</h1>
</div>

Upvotes: 0

Views: 91

Answers (2)

Keno
Keno

Reputation: 2098

It's not very efficient to search the entire body every time you click on each of the specified items.

This is what I'd do.

let headArtArray = $('.art-h .head-art'); //Assign it to a variable early to reduce searching

$('.rel-head').click(function() {
  let el = $(this);
  let text = el.text();

  for (let i = 0; i < headArtArray.length; i++) {
    
    if (headArtArray[i].innerText.includes(text)) {
      el.parent().fadeIn();
    } else {
      $(headArtArray[i]).fadeOut();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="art-h">
  <div class="head-art">some text</div>
</div>
<div class="art-h">
  <div class="head-art">anoter text</div>
</div>
<div class "related-heads">
  <h1 class="rel-head">some text</h1>
</div>

Upvotes: 0

guradio
guradio

Reputation: 15555

  1. Use selector :contains and concat the string properly.

$('.rel-head').click(function() {

  if ($('.art-h .head-art:contains('+$(this).text()+')')) {
    $(this).parent().fadeIn().siblings().fadeOut();
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="art-h">
  <div class="head-art">some text</div>
</div>
<div class="art-h">
  <div class="head-art">anoter text</div>
</div>
<div class "related-heads">
  <h1 class="rel-head">some text</h1>
</div>

Upvotes: 1

Related Questions