[英]Select parent DIV contents based on a containing class using jquery
我想抓取基於DIV
中的類的DIV
,例如,我的頁面將包含
<html>
<head></head>
<body>
<div>
<p class="foo">some text</p>
<p>test1</p>
<p>test 2</p>
</div>
</body>
</html>
結果將是:
<div>
<p class="foo">some text</p>
<p>test1</p>
<p>test 2</p>
</div>
我努力了
$.get("https://some.url.com/index.html", function(my_var) {
console.log($(my_var).closest('div').find('.foo'));
});
但是只是得到一個空的結果?
您應該首先找到.foo
,然后使用.closest()
選擇它的父.closest()
$.get("https://some.url.com/index.html", function(my_var) {
console.log($(my_var).find(".foo").closest('div'));
});
$(".foo").closest("div").css("color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <head> </head> <body> body <div> <p class="foo">some text</p> <p>test1</p> <p>test 2</p> </div> body </body> </html>
為了更好的方法,需要比找到特定的類find('.foo')
首先定位body
您可以查看以下工作示例:
$(document).ready(function(){ $('body').closest('body').find('.foo').css("color", "red") })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script> <html> <head> </head> <body> <div> <p class="foo">some text</p> <p>test1</p> <p>test 2</p> </div> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.