jQuery Selectors: Selects elements that have no content

If you have a <div>, <p> or other elements that have empty content, you could sieve them out and maybe fill them with other text string or data.

Note that in the selector, I have also chained a .css() to highlight the selected line to a different color.

So in the example below, line 17 will be selected and the newly added text will be highlighted to blue.

<!DOCTYPE html>
<html>
<head>
    <script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
    <script>
        $(function () {
            $('p:empty').html('I have some content now.').css('color', 'blue');
        });
    </script>
</head>
<body>
<div>
    <h4>Ushuaia</h4>

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

    <p></p>
</div>
<div>
    <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 End of the World Train.</p>

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

 

Series Navigation<< jQuery Selectors: Selects element that contains a specific child element $(‘has(E)’)
jQuery Selectors: Selects elements that have some content-parent >>