1

I am having trouble understanding why my selector is not working for a foreach loop.

My DOM looks as such:

<div id="page1" class="ui-droppable">

    <div class="ui-draggable ui-draggable-handle ui-draggable-dragging signatureInstance selected btn-delete" style="position: absolute; left: 185px; top: 470px;">
        <img src="http://example.com/img/field.png">
        <span class="glyphicon glyphicon-remove btn-delete"><span></span></span>
    </div>

    <div class="ui-draggable ui-draggable-handle ui-draggable-dragging signatureInstance selected btn-delete" style="position: absolute; left: 171px; top: 562px;">
        <img src="http://example.com/img/field.png">
        <span class="glyphicon glyphicon-remove btn-delete"><span></span></span>
    </div>

</div>

Would someone kindly explain why the following selector is not valid for a foreach iteration?

$('#page1 .signatureInstance').forEach(function(index) {
    console.log($(this));
});

or

$('#page1 .ui-draggable .ui-draggable-handle .ui-draggable-dragging signatureInstance .selected .btn-delete').forEach(function(index) {
    console.log($(this));
});

or even:

$('#page1 div').forEach(function(index) {
    console.log($(this));
});

1 Answer 1

2

You need to use each() for iterate over jQuery object, it's built for it.

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. ( Taken from https://api.jquery.com/each/ )

Array.prototype.forEach() using for iterate an array not for jQuery object colection.

$('#page1 .signatureInstance').each(function(index) {
    console.log($(this));
});

For a better understanding Iterating over jQuery and non-jQuery Objects

Sign up to request clarification or add additional context in comments.

2 Comments

Well I feel silly. Thank you. I really appreciate the help!
@Nathan_Sharktek : glad to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.