jquery filtering has + not

FFish picture FFish · Oct 28, 2010 · Viewed 39.7k times · Source

Okay I have list items, some have a span, some not.
On my event I want to add the span when they don't have any yet.

has() works fine, but not() adds the span to both??

HTML:

<ul>
    <li>
        <p>item</p>
        <span class="spn">empty span</span>
    </li>
    <li>
        <p>item 2</p>
    </li>
<ul>
<hr>
<a class="add-span"href="#">check</a>

JS:

$("a.add-span").click(function() {
    $("li").each(function(index) {
        // $(this).has("span").find("span").append(" - appended");
        $(this).not("span").append('<span class="spn">new span<\/span>');
    })    
})

Answer

John Hartsock picture John Hartsock · Oct 28, 2010

You can use a combination of the :not and :has selectors like this

$("a.add-span").click(function() {
    $("li:not(:has(span))").each(function(index) {
        $(this).append('<span class="spn">new span<\/span>');
    });
});

Here is a demo http://www.jsfiddle.net/xU6fV/