Jason Wells
Jason Wells

Reputation: 889

Returning true or false in JQuery in a selector?

If I have a string of text in a element, what is the most efficient way in jQuery to return if that text matches a given string.

E.G,

<div id="myDiv">This is a test</div>

$("#myDiv").eq("This is as test"); // returns true or false

But eq is not the right function

Upvotes: 1

Views: 148

Answers (3)

Glorious Kale
Glorious Kale

Reputation: 1313

if($("#myDiv").text() === 'This is a test'){ /* true */ }else{ /* false /* }

Upvotes: 0

grammar31
grammar31

Reputation: 2060

jQuery:

$('#myDiv').text() === "This is as test";

Note, this gets ugly if the DOM contains other nodes or weird spacing, etc. But for simple nodes you control, that's the simplest way.

Upvotes: 9

adeneo
adeneo

Reputation: 318212

I'd use the grammar31 solution myself, but just for fun, here are some other ways:

$("#myDiv:contains('This is a test')")​.length​==1;
document.getElementById('myDiv').innerHTML == 'This is a test';

Upvotes: 3

Related Questions