I have following html code:
<ul>
<li>Parameter1</li>
<li>Group1
<ul>
<li>Parameter2</li>
<li>Parameter3</li>
</ul>
</li>
<li>Parameter4</li>
<li>Group2
<ul>
<li>Parameter5</li>
</ul>
</li>
</ul>
And when I trigger onClick method on any of the LI elements, I need to get closest previous LI element.
If I click Parameter4 I need Parameter3 element.
If I click Parameter5 I need Group2 element.
I know the basics of prev(), closest(), find(), but I am not able to make it work.
element.prev('li') ignores nested LIs in UL
I think I am able to write the logic in words: I need previous LI element element.prev('li') and if this element has UL inside, I want last LI in that. If it has no UL, return the prev('li') that we started with.
Thank you.
Hey you can do something like this.. i tested this locally and it's working...
<ul>
<li>Parameter1</li>
<li>Group1
<ul>
<li>Parameter2</li>
<li>Parameter3</li>
</ul>
</li>
<li>Parameter4</li>
<li>Group2
<ul>
<li>Parameter5</li>
</ul>
</li>
</ul>
and jQuery like this
<script type="text/javascript">
$('li').on('click',function(event) {
event.stopPropagation();
if ($(this).children("ul").length > 0) {
if($(this).prev('li').length > 0) {
console.log($(this).prev('li').text());
}
} else if ($(this).prev('li').length > 0 && $(this).prev('li').children("ul").length > 0 ) {
console.log($(this).prev('li').children("ul").find("li:last").text());
} else if($(this).prev('li').length > 0) {
console.log($(this).prev('li').clone().children().remove().end().text());
} else if ($(this).is(":first-child")) {
console.log($(this).parent('ul').parent('li').clone().children().remove().end().text().trim());
} else {
console.log($(this).closest('ul').prev('li').text());
}
});
</script>
PS: Don't forget too include jQuery
Try this :
$('ul li').click(function(e) {
var element = $(this);
if(element.prevAll('li').length > 0) {
element.prev('li').text();
} else {
element.closest('ul').parent('li').text();
}
e.stopImmediatePropagation();
});
You can try testing each element to see if the previous has a list and take the last element or if the element is part of a parent list and take the parent list value:
$('li').click(function(e) {
e.stopPropagation()
var prev = $(e.target).prev();
var parent = $(e.target).parent().closest('li');
if (prev.find('ul li').length) {
console.log(prev.find('ul li:last').text());
} else
if (parent.length && !prev.length) {
console.log(parent.clone().find('ul').remove().end().text())
} else {
console.log(prev.text());
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Parameter1</li>
<li>Group1
<ul>
<li>Parameter2</li>
<li>Parameter3</li>
<li>GroupX
<ul>
<li>ParameterX</li>
</ul>
</li>
</ul>
</li>
<li>Parameter4</li>
<li>Group2
<ul>
<li>Parameter5</li>
</ul>
</li>
</ul>