4

i have an ul with some li something like this

<?php
   for($i=0; $i<5; i++) { 
      $id_name = "link" . $i;
      echo "<ul><a href='#' id=$id_name >list</a>
               <li class='on'>1</li>
               <li class='on'>2</li>
               <li class='on'>3</li>
            </ul> ";
    }
?>

and css :

.off{display:none;} .on{display:block;}

I want every time I click a link to hide all li elements of this link. I tried jQuery with toggleClass() function but I can't do nothing is I don't know the id of the link. I read something about child() and parent() functions. Can I use this way? (sorry for the programming mistakes i am new to php)

1
  • The only valid children of <ul> tags are <li> tags ... I'd fix the HTML first then work on the JavaScript (as the structure will be different)... Commented Dec 9, 2015 at 9:00

3 Answers 3

2

Why not giving a link tag some class name as example myLink, like following code :

echo "<ul><a href='#' id=$id_name class='myLink'>list</a>
           <li class='on'>1</li>
           <li class='on'>2</li>
           <li class='on'>3</li>
        </ul>

And later on in jquery you can target myLink class name and use .siblings() as A tag are siblings of li element.Thus no need for .child() or .parent(). See following code :

$(document).on('click', '.myLink', function () {
  $(this).siblings().toggleClass('off');
});

One thing to consider, if you defined already on class name on li element, using toggleClass('off') would only add and remove off class name but not the on class name. To get desire result, use this css :

.off {
  display:none !important;
} 

DEMO

p/s : A tag should not be there as it not a valid markup for UL

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, as worst HTML structured would broken jquery code.
1

Try:

$('a').click(function(){
 $(this).parent().find('li').toggleClass('off');
});

or :

 $('a').click(function(){
     $(this).parent().children('li').toggleClass('off');
    });

or:

$('a').click(function(e){
  e.preventDefault();
     $(this).nextAll('li').toggleClass('off');
    });

1 Comment

Think you might want $(this).parent().find() ... ? Though, admittedly the HTML is badly structured.
1

If you are using jquery you can just add a function in your html. No need to have a class for hiding and showing (unless you are applying animations or something to your css classes). As mentioned by another user, you should remove the anchor from your list and place it outside or as a list item itself.

$(document).ready(function() {
  $('a').click(function() {
    $(this).parent().children('li').toggle();
  });
});

Comments

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.