1

I have this wordpress blog that has many pages with subpages that dropdown on hover.... the thing is, I dont want the pages that you hover to link to anything unless they dont have any ul with many anchors inside so just the subpages will have a href different than "#" So basically Im hacking my way through this with some simple javascript.

   jQuery(document).ready(function(){
   jQuery("#menus li > a").attr("href","#");
 });

This is selecting every a.. and I dont want that... I just want the anchors that are main pages, not subpages... heres the html so maybe you can think of a better way to select this.

Ill explain first

the structure is an ul with many li that have an anchor inside if the li also has a ul inside then those are subpages that will appear on hover. hence the initial anchor should have href="#" if there is no ul inside the li then the li a should keep its href.

    <ul id="menus">
      <li>
        <a href="somelink">Main Page</a> //href should be changed to #
        <ul>
            <li>
              <a href="somelink2/">Subpage1</a>
            </li>
            <li>
              <a href="somelink3">Subpage2</a>
            </li>
        </ul>
      </li>
      <li>
        <a href="somelink">MainPage-with-no-subpages</a> //href should not be changed
      </li>
      <li>
        <a href="somelink4">MainPage</a> //href should be changed to #
        <ul>
          <li>
            <a href="somelink5">Subpage</a>
          </li>
          <li>
            <a href="somelink6">Subpage</a>
          </li>
        </ul>
      </li>
</ul>

2 Answers 2

2

try

jQuery(document).ready(function(){
   jQuery("#menus li > ul").siblings('a').attr("href","#");
});
Sign up to request clarification or add additional context in comments.

2 Comments

Ignore whatever I said in my answer. I did not read your question correctly. Reigel is absoutely correct.
` if there is no ul inside the li then the li a should keep its href., so, my approach is to find the ul... then change the href of <a>... if no ul, href of <a>` remains....
0

This should do what you want:

jQuery(document).ready(function(){
   jQuery("#menus li:has(ul) > a").attr("href","#");
}

2 Comments

using a non-standard selector like :not, :has, etc... is slow... as much as possible, try not using them...
I'm aware there's an overhead but I was of the impression it's no more slow than traversing up and then back down the DOM like the other answers? Correct me if I'm wrong...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.