Reputation: 9668
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:
<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
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
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
Reputation: 2844
.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