gpt4 book ai didi

javascript - 按类名称获取上一个/以上元素

转载 作者:行者123 更新时间:2023-11-28 20:50:48 25 4
gpt4 key购买 nike

让我们估计一下元素的排列如下:

<div><input class="elementToGet" value="1"></div>           // st elementToGet
<div><span class"button">get prev elementToGet</span></div> // Nr1
<div><span class"button">get prev elementToGet</span></div> // Nr2
<div><span class"button">get prev elementToGet</span></div> // Nr3
<div><input class="elementToGet" value="2"></div> // nd elementToGet
<div><span class"button">get prev elementToGet</span></div> // Nr4
<div><span class"button">get prev elementToGet</span></div> // Nr5
<div><span class"button">get prev elementToGet</span></div> // Nr6

如何获取每个跨度的前一个 elementToGet

例如,从 4 开始编号的元素将获得第二个 elementToGet

无需框架的 JavaScript。

function getPrev(className) {
var items = [], myPosts = document.getElementsByClassName(className);

for (var i = 0; i < myPosts.length; i++) {

// I have no ideas what to do next

items.push(myPosts[i]);
}
return items[0];
}

最佳答案

要获得您想要的,您可以使用 parentNode 获取 div周围span 。然后你可以使用 previousSibling 遍历 DOM 并使用 childNodes firstChild 找到您想要的输入。

我这么快就破解了:

var span = document.getElementsByClassName('button')[4], // one of the "button" spans
div = span.parentNode, // get the span's parent div
ele, // variable to hold the element we are looking for
temp; // temp var for the loop

while ((div = div.previousSibling) !== null) { // Loop through all the previous divs
temp = div.firstChild; // get the div's children
if (temp && temp.className === 'elementToGet') { // does it's 1st child have the class?
ele = temp; // we found it!
break;
}
}
alert(ele.value);​

演示:http://jsfiddle.net/zH4SU/1/

关于javascript - 按类名称获取上一个/以上元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12480886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com