javascript - 在类为 ="B"的元素中获取类为 ="A"的 DOM 元素

标签 javascript html

具有这种 HTML 结构:

<div class="fruit">
  <div class="tomato">get this one</div>
</div>
<div class="vegetable">
  <div class="tomato">not this one</div>
</div>

如何使用 Javascript 获取 .fruit 元素内的 .tomato 元素,而不是 .vegetable 内的元素?

例子:

a = document.getElementsByClassName("fruit");
b = a.FunctionThatGetsTheClass("tomato");

最佳答案

另一种方法是使用选择器和函数 Document.querySelectorAll

The Element method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

let tomatos = document.querySelectorAll('.fruit .tomato');

let tomatos = document.querySelectorAll('.fruit .tomato');
// The function map is only to demonstrate the selected elements.
console.log(Array.from(tomatos).map(d => d.textContent));
<div class="fruit">
  <div class='tomato'>tomatos#1</div>
  <div class='tomato'>tomatos#2</div>
</div>
<div class="vegetable">
  <div class='tomato'>tomatos#3</div>
  <div class='tomato'>tomatos#4</div>
</div>

关于javascript - 在类为 ="B"的元素中获取类为 ="A"的 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53018287/

相关文章:

javascript - Backbone.js 获取实际上不设置属性

在字符串中遇到换行符时,Javascript 在 Visual Force 页面上不起作用

html - 自动完成 intellij - less/css

javascript - 在生成的 HTML 中注入(inject)或初始化 Vue 组件

javascript - 在选中单选按钮之前禁用输入字段 (HTML)

javascript - 响应式 JS - 调整窗口大小时出现问题

javascript - HTML 中的 SVG 文件

javascript - 如何将两种不同类型应用于 sigma.js 中的边缘

html - 如何在多个div元素之间添加垂直线

javascript - .indexOf() 和 window.open