Nathaniel MacIver
Nathaniel MacIver

Reputation: 397

JQuery .find() can find by id, but not by class

I've created the following DOM using Jquery:

<div id="d0" class="choiceDiv">
    <input type="checkbox" id="cb0" class=".userCheckBox" value="Option 1" checked="checked">
    <input type="hidden" id="h0" class=".userCheckBoxHidden" value="true">
    <label for="cb0">Option 1</label>
</div>

I've applied CSS tags to my elements in the DOM, through the CSS classes do not have any properties inside of them at this point.

There are about 17 of these in a div. After the page has been loaded, I'd like to reload the current checked value of each checkbox. As I iterate through each code, I try to use the .find() function on the DOM:

$('.choiceDiv').each(function(e){

When I try to find by Class,

$(this).find('.userCheckBox');

I get the following failure Object:

init [prevObject: init(1), context: div#d0.choiceDiv, selector: ".userCheckBox"]
context: div#d0.choiceDiv
length: 0
prevObject:init [div#d0.choiceDiv, context: div#d0.choiceDiv]
selector:".userCheckBox"
__proto__:Object(0)

When I try to find by ID,

$(this).find('#cb'+e)[0];

I get what I'm looking for:

<input type="checkbox" id="cb0" class=".userCheckBox" value="Option 1" checked="checked">

I was hoping to pull the object by class to ensure I always get the type of input I'm looking for. Can someone explain why I can use .find() with an ID and not by Class in this instance? I tried figuring it out with this post but couldn't get it to work.

Upvotes: 3

Views: 17461

Answers (1)

Cameron Sumpter
Cameron Sumpter

Reputation: 454

Just remove the period from the class attribute. For example:

<input type="checkbox" id="cb0" class="userCheckBox" value="Option 1" checked="checked">

Could be found via .find('.userCheckBox') or .find('#cb0').

Upvotes: 7

Related Questions