BGundlach
BGundlach

Reputation: 279

find which child of parent element jquery

So I can find if an element is a child of a parent, but I can't figure out how to get the index of the current element in the parent element. For example. I have collapsing articles on my page http://gundlach-marketing.com/dev, in order to reset the margins I need to know what article number they are.

var articleId = $(this).attr('id');
var articleIndex;
$(this).parent().children('article').each(function (index) {
    if ($(this).attr('id') == articleId) {articleIndex = index}
});

the above code works, It's just inelegant. There has to be a better way! What is it?

Upvotes: 1

Views: 107

Answers (2)

megawac
megawac

Reputation: 11373

Use $ele.index

var $this = $(this);
var articleId = $this.prop('id');
var $article = $this.find("#" + articleId);
var index = $this.siblings('article').index($article);

If you are trying to find the index of this then just use

var index $(this).parent().getChildren('articles').index(this);

Upvotes: 2

isherwood
isherwood

Reputation: 61114

$(this).parent().children() 

is equivalent to

$(this).siblings()

no? And

$(this).index()

might just do the job of both.

http://jsfiddle.net/isherwood/VChu4/

Upvotes: 1

Related Questions