Reputation: 173
How to make a specific target for tag element, since I want to add some class for the specific i
tag with class icon
, while the parent li
target is collapsed the ul
:
$('ul li').on('click', function(e) {
e.stopPropagation();
$(this).children('ul').slideToggle('slow', function() {
// add class to the 'i' tag element
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<a>
<li>
<span>Menu</span>
<span><i class="icon"></i></span>
<ul>
<a><li>Sub menu1</li></a>
<a><li>Sub menu1</li></a>
</ul>
</li>
</a>
<a>
<li>Other Menu</li>
</a>
<a>
<li>Other Menu</li>
</a>
<a>
<li>Other Menu</li>
</a>
<a>
<li>
<span>Menu</span>
<span><i class="icon"></i></span>
<ul>
<a><li>Sub menu1</li></a>
<a><li>Sub menu1</li></a>
</ul>
</li>
</a>
</ul>
Upvotes: 0
Views: 75
Reputation:
You can save the link that you click and use it later, I think, adding preventDefault
is a good way to prevent scrolling page.
$('ul li').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
const $link = $(e.target);
$link.children('ul').slideToggle('slow', function() {
$link.find('i').addClass('aclass');
});
})
Upvotes: 0
Reputation: 1246
You can try this without changing any of your existing code.
$('ul li').on('click', function(e) {
e.stopPropagation();
$(this).children('ul').slideToggle('slow', function() {
// add class to the 'i' tag element
$(this).prev().find("span>i.icon").addClass("someclass");
});
});
Upvotes: 0
Reputation: 10879
You can store the clicked <li>
element in a local variable, e.g. $this
. Then from inside the slideToggle()
callback, you can just re-use it and find()
your <i>
inside.
Also, your closing <a>
tags were wrong, it has to be </a>
, not <a/>
. And a <ul>
can only have <li>
elements as direct child nodes. If what you were trieng to achieve by that was merely to have a hand cursor, you can just set cursor: pointer
vias CSS, or have the links directly inside the <li>
s.
Working example with a demo class to show it having any effect:
$('ul li').on('click', function(e) {
e.stopPropagation();
var $this = $(this);
$this.children('ul').slideToggle('slow', function() {
$this.find('i').addClass('aclass');
});
})
/* test style: */
ul li {
cursor: pointer;
}
ul li i.aclass {
border: solid red 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<span>Menu</span>
<span><i class="icon"></i></span>
<ul>
<a><li>Sub menu1</li></a>
<a><li>Sub menu1</li></a>
</ul>
</li>
<li>Other Menu</li>
<li>Other Menu</li>
<li>Other Menu</li>
<li>
<span>Menu</span>
<span><i class="icon"></i></span>
<ul>
<a><li>Sub menu1</li></a>
<a><li>Sub menu1</li></a>
</ul>
</li>
</ul>
Upvotes: 2