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.
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"); }); }); 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 .