简体   繁体   English

使用jquery根据包含的类选择父DIV内容

[英]Select parent DIV contents based on a containing class using jquery

I would like to scrape the contents of a DIV based on a class within the DIV for example, my page would contain 我想抓取基于DIV中的类的DIV ,例如,我的页面将包含

<html>
  <head></head>
  <body>
    <div>
      <p class="foo">some text</p>
      <p>test1</p>
      <p>test 2</p>
    </div>
  </body>
</html>

The result would be: 结果将是:

<div>
  <p class="foo">some text</p>
  <p>test1</p>
  <p>test 2</p>
</div>

I have tried 我努力了

$.get("https://some.url.com/index.html", function(my_var) {
  console.log($(my_var).closest('div').find('.foo'));  
});

But just get an empty result? 但是只是得到一个空的结果?

You should first find .foo and then select parent of it using .closest() 您应该首先找到.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> 

For Better approach need to target body first than find your particular class find('.foo') you can view the working example as below : 为了更好的方法,需要比找到特定的类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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM