jQuery find if div with id=X exists inside a DOM string
I'm trying to check if a div with an id exists in a string holding some html, so I'm looking for a function that returns true or false.
There's a function hasClass that checks if a div has a certain class
$('#mydiv').hasClass('bar')
I guess what I'm looking for is somethin开发者_运维问答g like
var mystring = "some string with html";
mystring.hasId('lookingforthisid');
How can I check this?
Turn it to a jquery object and use the .find()
method to locate the element you want
var mystring = "some string with html";
var $mystring = $('<div>' + mystring + '</div>');
alert( $mystring.find('#lookingforthisid').length );
if it has .length
greater than 0 then it exists..
Improvement / Generalization
If you want to make a general function to check if strings contain some jquery selector you can do this
String.prototype.hasSelector = function( aSelector ){
return ($( '<div>' + this.toString() +'</div>').find( aSelector ).length>0) ? true : false;
};
and use it like this
var mystring = 'test <div id="someid">text in ID</div> outer <div class="someclass">text in class</div> ';
alert( mystring.hasSelector('#someid') );
alert( mystring.hasSelector('.someclass') );
Live example at http://www.jsfiddle.net/gaby/Ajp7K/
jquery find if div with id=X exists
Use the length
:
if($('#mydiv').length > 0){
// element exists
}
else{
// element does not exist
}
You can convert it to a function like this:
function element_exists(id){
if($(id).length > 0){
return true;
}
return false;
}
And use like:
if (element_exists('#some_id')){
// element exists
}
else{
// element doesn't exists
}
If you want to check if an element with certain class exists, you can use hasClass
method instead.
If you want to check if an element with certain piece of text exists, you can use the :contains
filter selector instead. Here is an example:
alert($('#element_id:contains("some text")').length);
find if element exists within a string of HTML:
if($("div#mydiv", mystring).length >= 1) {
return true;
} else {
return false;
}
精彩评论