sonam
sonam

Reputation: 3760

looping through elements jquery selector

I have to select elements which contains id attribute and class attribute having 'child-of-' value and loop through the elements returned by the selector.

So far i could write:

$('.child-of-').each(function(){
...
});

This selects all the elements having class of child-of- including elements which does not have id also. There are elements which has that class but does not have any id attribute. so How can i select elements which has 'id' attribute and id has some value and also has class of child-of-. ?

For example

 <div id="any1" class="child-of-"></div>
 <div id="any2" class="child-of-"></div>
 <div class="child-of-"></div>

Only the div having id attribute must be selected. ie the first two divs in the example. the third does not have id attribute value and hence should not be selected

Upvotes: 2

Views: 1507

Answers (4)

Jay Blanchard
Jay Blanchard

Reputation: 34416

To get the attribute values you would use the attribute selectors:

$('[id*="child-of-"][class*="child-of-"]').each(function...

Substring attribute selectors - http://api.jquery.com/attribute-contains-selector/

Upvotes: 0

noj
noj

Reputation: 6759

$('[id].child-of-').each(function(){
    ...
});

Upvotes: 1

Ram
Ram

Reputation: 144659

You can use attribute selector.

$('.child-of-[id]').each(function(){
    ...
});

Fiddle


If your classes starts with child-of- you can use attribute starts with selector:

$('[class^="child-of-"][id]').each(function(){
    ...
});

Upvotes: 3

gabitzish
gabitzish

Reputation: 9691

You can use this selector:

$('#child-of-.child-of-').each(function(){
    ...
});

Upvotes: 0

Related Questions