Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - rule for "does not contain element"

Tags:

jquery

I want to create a rule to target the a element in the following:

<ul id="root">
   <li>
      <a href="item.html">Root Menu Item</a>
   </li>
</ul>

However this should not apply if the li element contains another ul element, e.g:

<ul id="root">
   <li>
      <a href="#">Sub Menu</a>
      <ul>
         <li>
            <a href="item.html">Sub Menu Item</a>
        </li>
      </ul>
   </li>
</ul>

I have created the event as required but need it to only work on the "root" menu items.

I know I can just add an id attribute to target the desired element only but the menu plugin that my client has installed is not easily configurable.

like image 869
MAX POWER Avatar asked Jul 09 '10 16:07

MAX POWER


2 Answers

If you're matching the a do this:

var result  = $('#root > li:not(:has(ul)) > a');
  • http://api.jquery.com/not-selector/
  • http://api.jquery.com/has-selector/

If you want to allow deeper nested <ul> elements, and just want to check to make sure only the direct children don't have a <ul>, you could do this:

var result  = $('#root > li:not(:has(> ul)) > a');

EDIT:

To have more than one selector at the same time, separate them with a comma inside the quotes:

var result  = $('#root > li:not(:has(> ul)) > a, #someOtherElement');
like image 162
user113716 Avatar answered Oct 21 '22 21:10

user113716


$('#root a').click(function(e) {
    if ( $(this).parents('ul').length > 1 ) {
       e.preventDefault(); // cancel action for anchors inside of #root who have multiple parent list elements 
    }
});

Change logic per requirement.

like image 2
meder omuraliev Avatar answered Oct 21 '22 22:10

meder omuraliev