Shane Adrian Muaz Shane Adrian Muaz - 9 months ago 25
Javascript Question

jQuery selector to target the control right before current element

I am trying to select the element right BEFORE current element. The current element is a hyperlink which when clicked appends some text to the "target" which is just before the hyperlink.

These controls are in asp:repeater so the same sequence gets repeated over and over and every hyperlink should be able to identify the element just above it.

here is my DOM screenshot

enter image description here

I just need to know how to select the element this way ! thanks


You can use either previousSibling:

var as = document.getElementsByTagName('a');

for (var i=0, len=as.length;i<len;i++){
    as[i].onclick = function(e){
        var previous;
        if (this.previousSibling.nodeName == '#text') {
            // the previousSibling was a textnode, comprising of the whitespace between elements
            previous = this.previousSibling.previousSibling;
        else {
            previous = this.previousSibling;
        } = 'yellow';

JS Fiddle demo.

Or use jQuery's prev():


JS Fiddle demo.