Reputation: 1596
I'm fairly new to jQuery and javascript in general, and I'm looking to return only the DOM elements which have a class defined. For example:
<div id="myObject">
<h2>hello world</h2>
<div class="foo">bar</div>
<div class="bar">foo</div>
<div></div><a href="http://google.com"></a>
</div>
I'm wondering if there exists a jQuery function or a clever search parameter I can pass to $(#myObject).find(...)
which would return only .foo
and .bar
, since those are the only two DOM elements which have a class defined. To generalize, would it also be possible to search for the presence of any attribute?
It seems I can do this using a more complex string of function calls, such as
var toReturn = [];
var descendants = $('#myObject').find('*');
$.map(descendants, function (element, index) {
if(element.getAttribute('class') != undefined){
toReturn.push(element);
}
});
But if there's something simpler, it would be helpful to know about it.
Upvotes: 1
Views: 43
Reputation: 35670
Use $('#myObject [class]:not([class=""])')
. It will select all descendants of #myObject
that have a class defined, and it will exclude elements that have had a class removed. (Thanks to @TravisJ for the not
syntax!)
Snippet:
$('.byebye').removeClass('byebye');
$('#myObject [class]:not([class=""])').addClass('selected');
.selected {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myObject">
<h2>hello world</h2>
<div class="foo">bar</div>
<div class="bar">foo</div>
<div class="byebye">
class removed
</div>
<div>
no class here
</div>
<a href="http://google.com">none here either</a>
</div>
Upvotes: 3