MeltingDog
MeltingDog

Reputation: 15404

Jquery: Removing href attribute of parent list items

I have a menu consisting of a couplde of <ul>s nested within a couple of <li>s. eg:

<ul>
<li><a href="somewhere.html">Item 1</a></li>
<li><a href="somewhere.html">Item 2</a></li>
<li><a href="somewhere.html">Item 3</a>
  <ul>
    <li><a href="somewhere.html">Sub Item 1</a></li>
    <li><a href="somewhere.html">Sub Item 2</a></li>
  </ul>
</li>
</ul>

For the <li>s with nested <ul>s I want to replace their href attributes with #, eg:

<li><a href="somewhere.html">Item 2</a></li>
<li><a href="#">Item 3</a>
      <ul>
        <li><a href="somewhere.html">Sub Item 1</a></li>

I have written this script to do that, but it seems to affect all a tags within both lists.

$.each($("#menu ul li"), function() {
  if($(this).has("ul")){
   $(this).find("a").attr("href", "#");
  };
});

Was wondering if some one could tell me where Ive gone wrong?

Upvotes: 0

Views: 2756

Answers (3)

Jai
Jai

Reputation: 74738

this will be fine: http://jsfiddle.net/H8JDy/

$('#menu ul li > ul').siblings('a').attr('href', '#'); // <---this does the trick

As commented by nbrooks there's no reason for it to be wrapped in the loop

Upvotes: 1

nbrooks
nbrooks

Reputation: 18233

Find nested <ul> elements, navigate to their parent <li>, select the <a> within that, and change the href.

$('li > ul').parent().children('a').attr('href', '#');


As for why your code doesn't work, that's due to two main issues. Firstly, find traverses all levels of descendants. What you are actually trying to do is just traverse first level descendants, so use children. Secondly, has (non-intuitively) doesn't return a bolean value, it simply filters the matched set to the necessary elements (so using it in an if is pointless, because any non-empty object evaluates to true). When corrected, your code would read:

$("#menu ul li").has("ul").children("a").attr("href", "#");

Either of these approaches will do what you need, but the second is more straightforward and so will probably yield better performance.

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

Check for dom if its have child like below.

$(this).children('ul').length

In your code its inside if conditions where you are checking using .has

Tested Working Code

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

    $(function()
    {
        $.each($("#menu ul li"), function()
        {
            if($(this).children('ul').length > 0)
            {
                $(this).find("a").attr("href", "#");
            };
        });
    });

</script>

<ul>
    <li><a href="somewhere.html">Item 1</a></li>
    <li><a href="somewhere.html">Item 2</a></li>
    <li><a href="somewhere.html">Item 3</a>
      <ul>
        <li><a href="somewhere.html">Sub Item 1</a></li>
        <li><a href="somewhere.html">Sub Item 2</a></li>
      </ul>
    </li>
</ul>

Upvotes: 1

Related Questions