Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a specific child from children array

I have an array of jQuery children which I keep in a variable:

var panels = panelsHolder.children('div');

Now, I want to address only one of those children, and I know its index, so I do as follows:

panels[currentpanel].addClass('show')

But I get an error, because the object returned by panels[currentpanel] isn't a jQuery object, it's a plane DOM element. So I'm forced to convert this to a jQuery object - like this: jQuery(panels[currentpanel]) - but there must be a way to get that object as a jQuery object from the array.

How do I do that?

like image 561
Lea Cohen Avatar asked Nov 26 '25 16:11

Lea Cohen


2 Answers

You have to use eq() to get jQuery object instead of DOM as you are getting right now.

panels.eq(currentpanel).addClass('show')
like image 88
Adil Avatar answered Nov 28 '25 07:11

Adil


The problem is that when you get the currentpanel index from panels you're getting the plain DOM object, not the jQuery object. You can fix this by surrounding it with $().

$(panels[currentpanel]).addClass('show');

EDIT: This looks like the quick and dirty way to do it as you need to 'cast' the object to a jQuery object again. eq() as Adil suggests is the way to go.

panels.eq(currentpanel).addClass('show')
like image 40
Daniel Imms Avatar answered Nov 28 '25 05:11

Daniel Imms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!