sdvnksv
sdvnksv

Reputation: 9668

Get element with certain ID using .is() method

This should be very simple, but I just can't make it work.

I am trying to find an element with certain ID using .is() method:

http://jsfiddle.net/4hbvgwnv/

<div id="foo">Some text</div>

$(document).ready(function() {
    var id = "foo";
    alert( $("div").is("#" + id).text() );
}):

But this just won't work. What am I doing wrong?

PS: I know I can select an element with $("#foo"), but I want to use the .is() method.

Upvotes: 0

Views: 22

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115232

You need to use filter() which filter elements based the selector. is() will return a Boolean value not the jQuery object, returns true at least one element is matched else returns false.

$(document).ready(function() {
  var id = "foo";
  alert($("div").filter("#" + id).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Some text</div>

Instead you can simply use selector $("div#" + id) which select div with that particular id. It will only select element is div.

$(document).ready(function() {
  var id = "foo";
  alert($("div#" + id).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="foo">Some text</div>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337590

is() returns a boolean, you should use filter() instead:

$("div").filter("#" + id).text()

That said, if you're searching by id, you don't need to bother with a parent selector at all:

$('#' + foo).text()

Upvotes: 0

Alexandre Beaudet
Alexandre Beaudet

Reputation: 2844

http://api.jquery.com/is/

.is() returns a boolean, if you check your developer console you got an error showing that "text" isn't valid ! Are you sure that .is() can be used for that intent ?


A solution that might work (kinda weird way to do it tho) : http://jsfiddle.net/4hbvgwnv/1/

$( document ).ready(function() {
   var id = "foo";
   if($("div").is("#" + id))
      alert($("div").text());
});

Upvotes: 0

Related Questions