jQuery Selectors: Selecting an element with an ancestor

This entry is part 18 of 33 in the series jQuery Selectors

There is an important set of jQuery selectors known as the hierarchy selectors.

These selectors allow you to select HTML elements based on the DOM hierarchy.

We first look at selecting an element <span> with a <div> ancestor.

Notice that the first <span> was not selected.

<!DOCTYPE html>
    <script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
        $(function () {
            $('div span').css('color', 'blue').css('font-size', '1.5em');


<p><span>Southernmost city in the world.</span></p>

    <p>The city centered around a prison built by the Argentine government.</p>

    <p>They also built a railway to the settlement, now a tourist attraction known as the
        <span>End of the World Train.</span></p>

    <a href='http://en.wikipedia.org/wiki/Ushuaia'>Visit us here.</a>

There are 2 .css functions and they are chained.  You can also construct the selector as:

$('div span').css({'color': 'blue', 'font-size': '1.5em'});


Series Navigation<< jQuery Selectors: Selects elements that have some content-parent
jQuery Selectors: Selects based on immediate child/parent relationship >>

Leave a comment

Leave a Reply