qadenza
qadenza

Reputation: 9293

shorter way to check if a title exists

Checking if a title already exists. Is there a shorter way? Something like:

if(test.exists.inside('.title'){...

var x = 0;
var test = $('#test').text();
$('.title').each(function(){
if($(this).text() == test){x = 1;}
});
if(x == 1){console.log('exists');}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>

<div id='test'>lorem</div>

Upvotes: 0

Views: 548

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

a lot of ways to do this :contains , filter() with indexOf() and filter() with text equal test.. depending on what you're trying to do

var x = 0;
var test = $('#test').text();
var Exists = $('.title:contains("'+test+'")').length;
console.log('Yes '+Exists+ ' title with text '+test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>

<div id='test'>lorem</div>

you can check also with for contains text check

$('.title:contains("'+test+'")').length > 0

OR for exact text check

$('.title').filter(function(){
  return $(this).text().trim() == test;
}).length > 0

Note: :contains and .indexOf search for the text contains text not the exact text .. by using $(this).text().trim() == test; this will return the exact text element

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

If you're just looking for shorter code, one option would be to invoke Array.prototype.some, and rather than store the result of .text() in a variable, invoke it every time, to save on characters typed:

if ([].some.call($('.title'), d => $(d).text() === $('#test').text())) {
  console.log('exists');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>

<div id='test'>lorem</div>

Personally, I'd prefer readability over code length:

const textToFind = $('#test').text();
const exists = Array.prototype.some.call(
  $('.title'),
  title => $(title).text() === textToFind
);
if (exists) {
  console.log('exists');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='title'>lorem</div>
<div class='title'>ipsum</div>
<div class='title'>lorema</div>
<div class='title'>ipsuma</div>

<div id='test'>lorem</div>

Upvotes: 1

Related Questions