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>'); }) })
The not() method returns elements that do not match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are returned from the selection, and those that match will be removed. This method is often used to remove one or more elements from a group of selected elements.
jQuery not() Method: This method returns elements that do not match a defined condition. This method specifies a condition. Elements that do not match the condition are returned, and those that match will be removed. Mostly this method is used to remove one or more than one elements from a group of selected elements.
jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
The jQuery filter() method can take the selector or a function as its argument to filters the set of matched elements based on a specific criteria.
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/
$("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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With