Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over each sibling element

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);
        });
    });
});
like image 222
Joel G Mathew Avatar asked Aug 10 '13 14:08

Joel G Mathew


2 Answers

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.

like image 52
Pointy Avatar answered Oct 12 '22 09:10

Pointy


siblings is a function, so it needs parentheses:

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

http://api.jquery.com/siblings/

like image 25
Nicklas Nygren Avatar answered Oct 12 '22 10:10

Nicklas Nygren