按类名获取上一个/上面的元素

时间:2012-09-18 16:10:39

标签: javascript

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

<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];
}

2 个答案:

答案 0 :(得分:2)

要获得您想要的内容,您可以使用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);​

DEMO:http://jsfiddle.net/zH4SU/1/

答案 1 :(得分:1)

如果您使用的是JQuery,可以使用.closest(),它会遍历DOM树