Kaivosukeltaja Kaivosukeltaja - 1 year ago 107
jQuery Question

Select inline elements without text siblings

I need to select inline HTML elements that are the only thing inside their parent element - that is, there is no text or other inline elements before or after them.

<p><img src="foo.jpg"></p><!-- This should be selected -->
<p>Hello world! <img src="bar.jpg"></p><!-- This should not -->

Any way to do this with CSS or jQuery? I've tried
but they match both of these elements.

Answer Source

.children() will be the selected children you desire. You could potentially add these to an array if you want to use them for later or just print them using console.log()

$('p').each(function() {
    if ($(this).text().length === 0) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download