How can I use jQuery methods on elements accessed by brackets notation?

前端 未结 2 1399
臣服心动
臣服心动 2021-01-16 02:55

Elements from jQuery object can be accessed by bracket notation, like so: $(\'div\')[0] But in this case jQuery methods cannot be used.

Any other way to

相关标签:
2条回答
  • 2021-01-16 03:14

    Wrap it in a jQuery object again:

    var element = $('div')[0]; // DOM element
    var $element = $(element); // jQuery object
    

    Better yet, just use a narrower selector in the first place:

    var $element = $('div:eq(0)');
    

    http://api.jquery.com/eq-selector/

    0 讨论(0)
  • 2021-01-16 03:22

    If you're trying to get the first jQuery object in a collection, use jQuery's eq() method:

    $collection.eq(0);
    

    You can also use the :eq() selector when creating the collection in the first place:

    var $collection = $('div:eq(0)');
    
    0 讨论(0)
提交回复
热议问题