I have the following HTML scheme:
<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 JavaScript part:
$(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 methods .removeAttr() and .attr(), but it does not work because .each() returns the elements prototype instead of its instance. Same problem on a simple for loop.
this
refers to the DOM element. To use jQuery functionality on this element you need to wrap it in a jQuery object, ie: $(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
like so: $(this)
to use it how you describe.
This is the expected behaviour as described in the jQuery documentation:
The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With