简体   繁体   中英

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

<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()

$.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 :

 $(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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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