0

There are multiple objects in a div. I want to get the id of all those elements by their class. the number of elements can vary. I am doing it as

arr= $(".listitem #checkBox").hasClass('checkedItem').attr('id');

but it return only the first item

and if I use it as

arr= $(".listitem #checkBox").hasClass('checkedItem').map(function() {
     return this.id;
}).get();

The error on console is Object true has no method 'map'

How I can get the Ids of all CheckedItems

3 Answers 3

2

The .hasClass() method returns a boolean indicating whether any elements in the jQuery object have that class, and a boolean doesn't have a .map() method.

Instead, make the class part of the selector, so that the jQuery object contains only elements with that class:

arr= $(".listitem #checkBox .checkedItem").map(function() {
     return this.id;
}).get();

Note that your original selector ".listitem #checkBox" should only ever match one or zero elements, because id is supposed to be unique. For that reason I have assumed above that you are trying to check elements that are descendants of #checkBox. Let me know the structure of your html and I can tweak the selector to match...

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

Comments

2

The problem here is that you are trying to query for multiple items, but you are using an ID to look up.

arr= $(".listitem #checkBox")....

(the #checkBox part)

This code will never return an array.

ID Attribute spec for HTML 4.01

Comments

0

Use this you will get all the id of checkeditems

var selected = new Array();
$('#checkbox input:checked').hasClass('checkedItem').each(function() {
    selected.push($(this).attr('id'));
});

1 Comment

I wrote the same, but hasClass() returns a boolean so this is not working.

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.