[英]Select elements whose specific descendants' HTML contains a specific text?
我想選擇所有具有cite
后代且該cite
后代的HTML包含一些text
div
。 我努力了:
$('div')
.filter('cite')
.filter(function() {
return $(this).html().match('text');
})
和這個:
$('div')
.filter('div cite')
.filter(function() {
return $(this).html().match('text');
})
但它不起作用。 這里缺少什么?
也就是說,我想在以下HTML中選擇第3個div
。
HTML:
<div id="abcd">text1 text2</div>
<div id="abccd">text1 text2</div>
<div id="abcccd">
<cite><b>text1</b>text2</cite>
</div>
<div id="abd">text1 text2</div>
編輯:我要選擇的不是 $('div cite')
。 我想選擇$('div')
,其中div
包含一個cite
后代,該cite
后代的內容包含一些文本。
使用:contains()
選擇器:
$("div").find("cite:contains('text')").closest("div");
感謝@JonSG:
OP。 在一個不同答案的注釋中已經問到,僅使用filter()可以完成此操作,而無需使用mostest()或parent()向上返回樹。 我不喜歡這個答案,但是您可以這樣做:
var target = $("div").filter(function() {
return $(this).find("cite:contains('text')").length !== 0;
});
$(target).css("background-color", "coral");
要么:
var target = $("div").filter(function() {
return /text/.test($(this).find("cite").html());
});
$(target).css("background-color", "tomato");
那這個呢?
$("div").has("cite:contains('text')");
您可以嘗試以下方法:
$("div cite").each(function() {
` // $(this).text() get the text of cite`
});
為了達到預期的效果,請使用以下選項
$( "cite" ).each(function( index ) {
console.log( $( this ).text() );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.