Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery filtering has + not

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>');     })     }) 
like image 801
FFish Avatar asked Oct 28 '10 17:10

FFish


People also ask

Which is not jQuery method?

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.

Is not condition in jQuery?

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.

How use contains in jQuery?

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).

Which type of parameter can jQuery filter function take?

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.


2 Answers

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/

like image 93
John Hartsock Avatar answered Sep 22 '22 12:09

John Hartsock


$("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:

  • http://api.jquery.com/length/
  • http://api.jquery.com/children/
like image 40
Sarfraz Avatar answered Sep 22 '22 12:09

Sarfraz