How to compare two element text in JQuery?

Viewed 326

In my project, I am using Jquery. so I have two sections each section have multiple elements with different content, for example, left-content, and right-content. so left-content and right-content have the same class with multiple elements and right-content is dynamic and left-content is fixed one.

so if right-content text and left-content text are equal, then left-content that particular element we have add one new class.

I tried some of the ways but it not working as per my expectations. please help me fix this. if anything is wrong please correct me.

jQuery(document).ready(function(){
   let headingElement = jQuery('#articleTitle').text();

    jQuery('.ellipsis a').filter(function(){
        return jQuery(this).text() === headingElement;
    }).addClass('active');
});
.active{
  color:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="left-content">
  <div class="ellipsis">
    <a href="#">Terminology one</a>
  </div>
  <div class="ellipsis">
    <a href="#">Terminology two </a>
  </div>
  <div class="ellipsis">
    <a href="#">Terminology three</a>
  </div>
</div>

<div class="right-content">
  <h2 class="heading" id="articleTitle">Terminology two</h2>
</div>

2 Answers

You can use :contains this will check if the element has required text or not then addClass to that element.

Demo Code :

jQuery(document).ready(function() {
  let headingElement = jQuery('#articleTitle').text();
  jQuery('.ellipsis a:contains(' + headingElement + ')').addClass('active');
});
.active {
  color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="left-content">
  <div class="ellipsis">
    <a href="#">Terminology one</a>
  </div>
  <div class="ellipsis">
    <a href="#">Terminology two </a>
  </div>
  <div class="ellipsis">
    <a href="#">Terminology three</a>
  </div>
</div>

<div class="right-content">
  <h2 class="heading" id="articleTitle">Terminology two</h2>
</div>

I hope I understood your task correctly.

Was such a result necessary?

jQuery(document).ready(function(){
let headingElement = jQuery('#articleTitle').text();
  jQuery('.ellipsis a').each(function(){
    if (!$(this).text().indexOf(headingElement)) {
      $(this).addClass('active');
    }
  });
});
.active{
  color:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="left-content">
  <div class="ellipsis">
    <a href="#">Terminology one</a>
  </div>
  <div class="ellipsis">
    <a href="#">Terminology two </a>
  </div>
  <div class="ellipsis">
    <a href="#">Terminology three</a>
  </div>
</div>

<div class="right-content">
  <h2 class="heading" id="articleTitle">Terminology two</h2>
</div>

Related