假设我有这样的事情。
<div class="apple"></div>
<div class="apple"></div>
<div class="apple" id="MyElement"></div>
我想找到带有
class="apple"
的另一个元素在带有 id="MyEement" 的元素之前出现的次数,这样我可以稍后在 javascript 上使用 document.getElementsByClassName("class")[unknown] 修改它。有没有办法在绝对没有 jQuery 的情况下做到这一点?
我总是可以用 class=apple 来计算它之前的元素数量,但是我有很多元素都带有那个类名,所以有没有办法以编程方式做到这一点
直接使用elements数组,通过findIndex方法查找ID为“MyElement”的元素。 findIndex 返回的索引是元素在元素数组中的位置,因此我们可以直接使用它来确定在 ID 为“MyElement”的元素之前有多少个“apple”元素。
// Get all elements with the class name "apple"
const elements = document.getElementsByClassName("apple");
// Find the index position of the element with the ID "MyElement"
const myElementIndex = Array.prototype.findIndex.call(elements, (element) => element.id === "MyElement");
// Determine how many "apple" elements came before the element with ID "MyElement"
const numApplesBefore = myElementIndex;
console.log(numApplesBefore); // outputs: 2