views:

19

answers:

2

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>');
    })    
})
+3  A: 
$("a.add-span").click(function() {
    $("li").each(function(index) {
       if ($(this).children('span').length === 0){
         $(this).append('<span class="spn">new span<\/span>');
       }
    })    
})

With children() method, the length property is used to check whether or not a span already exits and if it doesn't, one is added/appended.

More Info:

Sarfraz
Didn't you mean `if($(this).children('span') ...`? But otherwise, +1. Didn't even think of that method. =)
Jeff Rupert
@Jeff Rupert: True, it is `children`, I did not focus on his selector. Thanks
Sarfraz
@Sarfraz... wouldint it be easier to just specify in the selector for the each function...IE $("li:not(:has(span))").each(...)
John Hartsock
@John Hartsock: Agreed but it didn't come in my mind at the time of writing and that is better actually :)
Sarfraz
@Sarfraz: You're welcome. I do it all the time myself.
Jeff Rupert
Thanks for digging this solution.
FFish
@FFish: Welcome :)
Sarfraz
+3  A: 

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/

John Hartsock
@FFish ... This is a cleaner solution
John Hartsock
yup +1 there :)
Sarfraz
Nice combination of not and has, at the end I choose Sarfraz option because I have another filter in the each loop, thanks!
FFish