Let’s estimate that we have elements arranged as below:
<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
How can I get the previous elementToGet for each span?
For example the elements numbered from 4 will get the second elementToGet.
Javascript with no frameworks needed.
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];
}
To get what you want, you can use
parentNodeto get thedivaround thespan. Then you can usepreviousSiblingto traverse the DOM and usechildNodesfirstChildto find the input you want.I hacked together this quickly:
DEMO: http://jsfiddle.net/zH4SU/1/