Teofrostus Teofrostus - 4 months ago 7
jQuery Question

How do you get all the descendents of a DOM element which have any class defined?

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>

I'm wondering if there exists a jQuery function or a clever search parameter I can pass to
which would return only
, 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){

But if there's something simpler, it would be helpful to know about it.


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!)



$('#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
    no class here
  <a href="http://google.com">none here either</a>