...">
    All geek questions in one place

    JQuery el.each () returns an HTMLAnchorElement element instead of an element instance

    I have the following HTML schema:

    <section id="vids"> <ul> <li> <a data-reference="12345" href="http://www.youtube.com/watch?v=12345" rel="external" target="_blank"> <span>Video 14</span> </a> </li> <!-- ... --> </ul> </section> 

    And the following part of JavaScript:

     $(document).ready(function() { console.log($("#vids a")); // Returns element instance collection $("#vids a").each(function(i, el) { console.log(this); // Returns HTMLAnchorElement instead of the element itself console.log(el); // Same here console.log(i); // Returns index }); }); 

    I need to use the .removeAttr () and .attr () methods, but this does not work because .each () returns a prototype of the elements instead of its instance. The same problem for a simple loop.

    +4
    javascript jquery for-loop each element
    headacheCoder Feb 24 '12 at 10:25
    source share
    2 answers

    this refers to the DOM element. To use jQuery functionality for this element, you need to wrap it in a jQuery object, i.e.: $(this) .

     $(document).ready(function() { console.log($("#vids a")); // Returns element instance collection $("#vids a").each(function(i, el) { console.log($(this)); // Will return [Object object] console.log($(el)); // Same var $el = $(this); $el.removeAttr("attribute").attr("foo", "bar"); }); }); 
    +10
    Rory mccrossan Feb 24 '12 at 10:29
    source share

    Wrap this as follows: $(this) to use it as you describe.

    This is the expected behavior described in the jQuery documentation :

    The .each () method is designed to simplify the construction of DOM loops and are less prone to errors. When it is called it itates over DOM elements that are part of the jQuery object. Each time the callback is executed, the current iteration of the loop has passed, starting from 0. Moreover, the callback is launched in the context of the current DOM element , therefore the this keyword refers to the element .

    +3
    Michael robinson Feb 24 '12 at 10:29
    source share

    Source: https://habr.com/ru/post/1398201/

    More articles:

    • MySQL filesort in GROUP BY YEAR & Month - mysql
    • nopcommerce MVC Route Description - asp.net-mvc
    • Backbone.js: workaround for implementing a slash url using pushstate in Internet Explorer - internet-explorer
    • Heroku push over https - git
    • Is this a variable undefined error in NodeJS or do I just need more sleep - javascript
    • Is parseInt () supposed to work like this? - javascript
    • Left offset can be set to ZERO - c ++
    • AnimationDrawable size scaling - android
    • Google Guice User Area - java
    • Codeigniter route regex - matches any line except 'admin' - regex

    All Articles

    Geek Questions | 2019