jquery - 查找包含在 HTML 标签中的元素

标签 jquery

如果我有以下 HTML 结构,我将如何抓取 h2 元素内的强标记之间的文本。

<div class="div1">
  <div class="div2>
   <h2>
     <strong>Default</strong>
     <span class="default">(Default)</span>
     <a class="remove remove-stage-1" href="#">Remove</a>
     <span class="remove remove-stage-2 hidden">
  </h2>

目前我正在控制台中尝试并想出了

template = $('.div1')
$(template).find('h2').each(function(index, elem) {
  console.log(index + $(this).text(), elem + $(this).text() );
});

这会将我的 elem 输出为

Default (Default) Remove

感谢任何帮助

最佳答案

使用Child Selector (“parent > child”)选择器。

<强> Live Demo

$('.div2 > h2 > strong').text()

描述:选择由“parent”指定的元素的“child”指定的所有直接子元素。

The child combinator (E > F) can be thought of as a more specific form of the descendant combinator (E F) in that it selects only first-level descendants.

关于jquery - 查找包含在 HTML 标签中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21933088/

相关文章:

javascript - javascript中的计数结果

jquery - 如何使用 Bootstrap 验证创建自定义 "Group Validation"?

ajax - 在同一页面中动态插入内容而不是转到新页面

jquery - 当通过 jQuery 应用类时,CSS 转换过渡在 Firefox 中不动画

javascript - 搜索具有某些类名的重复 ID

jquery - 使用 jQuery 模拟 anchor 点击的浏览器友好方式?

javascript - 奇怪的搜索表单行为

javascript - 如何在单个网页中拥有多个 Angular 应用程序?

javascript - 从本地协议(protocol)强制 Javascript 文件中的 http 协议(protocol)

javascript - Jquery 切换文本按钮,内部带有 Bootstrap 图标