gpt4 book ai didi

javascript - jQuery 查找 id=X 的 div 是否存在于 DOM 字符串中

转载 作者:行者123 更新时间:2023-11-30 23:42:32 28 4
gpt4 key购买 nike

我正在尝试检查带有 id 的 div 是否存在于包含某些 html 的字符串中,因此我正在寻找一个返回 true 或 false 的函数。

有一个函数 hasClass 可以检查 div 是否具有特定的类

$('#mydiv').hasClass('bar')

我想我正在寻找的是类似的东西

var mystring = "some string with html";

mystring.hasId('lookingforthisid');

如何检查?

最佳答案

将其转换为 jquery 对象并使用 .find()方法来定位你想要的元素

var mystring = "some string with html";

var $mystring = $('<div>' + mystring + '</div>');

alert( $mystring.find('#lookingforthisid').length );

如果有.length大于0则存在..

<小时/>

改进/概括

如果你想创建一个通用函数来检查字符串是否包含某些 jquery 选择器,你可以这样做

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/

关于javascript - jQuery 查找 id=X 的 div 是否存在于 DOM 字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4153784/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com