使用 jquery 基于包含类选择父 DIV 内容

Posted

技术标签:

【中文标题】使用 jquery 基于包含类选择父 DIV 内容【英文标题】:Select parent DIV contents based on a containing class using jquery 【发布时间】:2019-05-04 13:08:30 【问题描述】:

例如,我想根据 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'));  
);

但是只得到一个空结果?

【问题讨论】:

【参考方案1】:

您应该首先找到.foo,然后使用.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>

【讨论】:

【参考方案2】:

为了更好的方法需要首先定位body而不是找到您的特定类find('.foo'),您可以查看如下工作示例:

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

【讨论】:

以上是关于使用 jquery 基于包含类选择父 DIV 内容的主要内容,如果未能解决你的问题,请参考以下文章

Jquery - 在与此相同的容器类 div 中选择 div?

jQuery选择器

如何使用 jQuery 选择第一个父 DIV?

如果类包含某个字符串,则 div 中所有 <img> 的 jQuery 选择器

jQuery 选择与其他人共享类的单个 Div

jquery选择器