CLIX159 CLIX159 - 4 months ago 69
jQuery Question

Show first level children of a nested ul li using jquery

I have an HTML file like this:

<!DOCTYPE html>
<html lang="en-US"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title></title>
<style type="text/css">
.hide{display:none;}
</style>

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

function functionName(event) {
event.stopPropagation();
var item = event.data.param;
document.getElementById("list").innerHTML = item;
}

$(document).ready(function() {
$("li").each(function() {
$(this).on('click', {param: this.id}, functionName);
});
});

</script>
</head>

<body >
<div id="main">
<div id="tree">
<ul class="xyz">
<li class="hide">AVC</li>
<li class="hide">Anna</li>
<li class="hide">Peter</li>
<li id="foo1">Gary
<ul class="xyz">
<li class="hide">John</li>
<li class="hide">Anna</li>
<li id="foo2">Briton
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
<li id="foo3">Layla
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
<li id="foo4">Undertaker
<ul class="xyz">
<li class="hide">gg</li>
<li class="hide">hh</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

<div id="list"></div>

</div>




I have two div tags whose id is receptively
tree
and
list
. Tree div contains the nested
ul li
tags and each
li
have unique id.

I want to show the first level children of a
ul li
tag. For example, when I am clicking on
Gary
, it should show the first level children (
John, Anna, Britton
) in right
div i.e. list
.

Right now I am able to get the id of
ul li
element in
list
div when clicking any item.

How can I traverse the first level children of clicking element using jquery/javascript and display them in
list
div?

Thanks

Answer

Try using find() ,> ul selects the direct descendant

$('li[id^="foo"]').click(function(e){
e.stopPropagation();
var x = $(this).last().find(' > ul').clone().find('ul').remove().end();
console.log(x[0])
 $('#list').html(x);
 $('#list .hide').show();
});

simple demo : https://jsfiddle.net/sk30mwud/4/