Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery el.each() returns HTMLAnchorElement instead of elements instance

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.

like image 468
headacheCoder Avatar asked Dec 12 '22 05:12

headacheCoder


2 Answers

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");
    });
});
like image 130
Rory McCrossan Avatar answered Dec 14 '22 17:12

Rory McCrossan


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.

like image 27
Michael Robinson Avatar answered Dec 14 '22 19:12

Michael Robinson