jQuery查找DOM字符串中是否存在id = X的div [英] jQuery find if div with id=X exists inside a DOM string
问题描述
我正在尝试检查包含HTML的字符串中是否存在具有id的div,因此我正在寻找一个返回true或false的函数.
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.
有一个hasClass函数,用于检查div是否具有特定的类
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');
我该如何检查?
推荐答案
将其转换为jquery对象并使用 .find()
方法来查找所需元素
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 );
如果 .length
大于0,则表示存在..
if it has .length
greater than 0 then it exists..
改进/概括
如果您要创建一个通用功能来检查字符串是否包含某些jquery选择器,则可以执行此操作
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;
};
并像这样使用它
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') );
在 http://www.jsfiddle.net/gaby/Ajp7K/上的实时示例
这篇关于jQuery查找DOM字符串中是否存在id = X的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!