DA.
DA.

Reputation: 40673

jQuery selector to determine 'or'?

Let's say my HTML may look one of two ways:

Option 1:

<h2>My header
    <span class="apple">My Span</span>
</h2>

Option 2:

<h2>My header</h2>

Via jAuery, I want to append a span to either the nested span (if it's there) or to the header directly, resulting in one of these:

Option 1:

<h2>My header
    <span class="apple">My Span
        <span>My Span Inserted via jQuery</span>
    </span>
</h2>

Option 2:

<h2>My header
    <span>My Span Inserted via jQuery</span>
</h2>

Is there a clever selector that would detect both of the above scenarios? I could, of course, first check to see if my header has a span with a class of 'apple' within it. If so, do this, else, do that. I was wondering if there was a more elegant and less verbose solution, though.

Upvotes: 1

Views: 195

Answers (2)

tvanfosson
tvanfosson

Reputation: 532435

I think using a children filter and then andSelf() would work to get both. You could then use the first to choose the correct one. If children is empty then first will be the only element, that is, the header.

$('h2').each( function() {
    $(this).children('span')
           .andSelf()
           .filter(':first')
           .append('<span>My Span Inserted via JQuery</span>');
});

Updated to use filter() (instead of the second find).

Upvotes: 3

Martin Nycander
Martin Nycander

Reputation: 1309

The following selector selects all <h2>'s that does not have a <span> element or a <span> element which has <h2> as parent.

$("h2:not(:has(span)), h2 > span")
      .append("<span>My Span Inserted via jQuery</span>");

Upvotes: 7

Related Questions