开发者

Cant get jQuery methods to work

Why is it when I select html elements using .get(i) or similar methods, I am unable to use methods on those elements like the .removeClass() or .html().

I would think that the code below is perfectly valid, yet neither lines开发者_运维技巧 work. What do I need to do to apply jQuery methods to an element based on its ordinal index in the DOM?

($('li').get(0)).removeClass('yourClass');
$('li')[0].addClass('myClass');

Here is an example of the issue: http://jsfiddle.net/KcNWy/2/


Check the documentation:
The .get() method grants us access to the DOM nodes underlying each jQuery object.

You can DOM object into jQuery object again: $($('li').get(0)). Or, better yet, use eq: $('li').eq(0).

And also a debugging hint. You can use in firefox/chrome/safari console.log(myObject) to see what's actually returned.


The get() method passes back the DOM object

Retrieve the DOM elements matched by the jQuery object.

Try this instead:

$("li:eq(" + 0 + ")").removeClass("yourClass")

Working example: http://jsfiddle.net/KcNWy/6/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜