jQuery add class to object with .get() method

2019-02-22 17:28发布

问题:

running into a weird thing and I'm not sure what's going on.

I've grabbed the index of a DOM element via .index(), found a matching element via .get() and I'm trying to add a class to it via .addClass().

My console is returning the error: "Uncaught TypeError: Object #<HTMLLIElement> has no method 'addClass'"... which is especially odd because my Log shows the HTML element just fine (http://cloud.dhut.ch/image/2W3S0R3k2h2U)

Am I missing something? It's not returning in an array or anything. Confused.

Thanks!

JavaScript:

nFLi.get(active).addClass('active');

回答1:

You need to wrap it into a jquery object.

$(nFLi.get(active)).addClass('active');

Or you could use .eq method instead of .get, which returns a jquery object instead of original HTMLElement.

nFLi.eq(active).addClass('active');