Iterate over each sibling element

Joel G Mathew picture Joel G Mathew · Aug 10, 2013 · Viewed 19.4k times · Source

Context: I'm building a form and script which will perform an ajax query, based on clicking a specific button. There are multiple div blocks with elements of the same class, and based on the div block in which, a button is clicked, different forms will be processed.

As part of beginning the program, I have started with an apparently simple jQuery call.

I'm trying to add an onclick event to a specific class, and then trying to get the CSS value of the siblings of that element.

Error: I'm getting an error stating that TypeError: this.siblings is undefined.

Question: What is the proper way to iterate over siblings of an element using jQuery?

My code:

HTML:

<a class="btn LiveStatsBtn"><span class="btn-label">Get Stats now</span> </a>

JavaScript:

$(document).ready (function()
{ 
    $('.LiveStatsBtn').click(function(){
        this.siblings.each( function () {
            var tx=this.css();
            alert(tx);
        });
    });
});

Answer

Pointy picture Pointy · Aug 10, 2013

In a jQuery event handler, this refers to the DOM element, and is not a jQuery object. You have to wrap it in one:

$(this).siblings().each(function() {
  // ...
});

Also note that "siblings" is a function, so you have to call it to get a new jQuery object that wraps the element siblings.