Shane Adrian Muaz Shane Adrian Muaz - 5 months ago 9
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

Answer

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){
        e.preventDefault();
        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;
        }
        previous.style.backgroundColor = 'yellow';
    };
}

JS Fiddle demo.

Or use jQuery's prev():

$('a').click(
    function(e){
        e.preventDefault();
        $(this).prev('div').css('background-color','yellow');
    });

JS Fiddle demo.

References:

Comments