最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery find if div with id=X exists inside a DOM string - Stack Overflow

programmeradmin1浏览0评论

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 something like

var mystring = "some string with html";

mystring.hasId('lookingforthisid');

How can I check this?

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 something like

var mystring = "some string with html";

mystring.hasId('lookingforthisid');

How can I check this?

Share Improve this question edited Apr 11, 2011 at 15:46 bluish 27.4k28 gold badges125 silver badges184 bronze badges asked Nov 11, 2010 at 11:12 sarimotosarimoto 792 silver badges3 bronze badges 1
  • any reason for not using document.getElementById? – jebberwocky Commented Nov 11, 2010 at 13:29
Add a ment  | 

3 Answers 3

Reset to default 2

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/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;
}
发布评论

评论列表(0)

  1. 暂无评论