Reputation: 342
I have a HTML code of nested list giving me a hard time to read with jQuery!
I'm using
$.get();
to get the html then using
$(data).find(".thelist ul");
To get the list only which looks like
<ul>
<li><a href="Draft-Documents-Page_294813708.html">Draft Page</a>
<ul>
<li><a href="Batch-Closing-Version-3.7_295567410.html">Batch Version 7</a></li>
</ul>
</li>
<li><a href="Infection-Prevention-and-Control-System_491532.html">info Control System</a>
<ul>
<li><a href="About-info_261488773.html">About info</a></li>
</ul>
<ul>
<li><a href="Applicati.html">Application</a>
<ul>
<li><a href="Functionality.html">Functionality</a>
<ul>
<li>
<a href="Access.html">Access</a>
</li>
</ul>
<ul>
<li><a href="Login.html">Login</a>
</li>
</ul>
<ul>
<li><a href="info.html">info Desktop</a>
</li>
</ul>
<ul>
<li><a href="Search.html">Search</a>
</li>
</ul>
<ul>
<li><a href="info-Mobile.html">info Mobile</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<ul>
<li><a href="info.html">Support</a></li>
</ul>
<ul>
<li><a href="Technical.html">Technical Manual</a>
<ul>
<li><a href="Formatting.html">Formatting</a>
</li>
</ul>
<ul>
<li><a href="Troubleshooting.html">Troubleshooting</a></li>
</ul>
</li>
</ul>
</li>
</ul>
The actual list is more than 200 item! and it can go up to 7 levels!
What im getting is every item that has children the text is including all of their text!.
I need to get the text and the link of each then append or generate my own list with same level but different html structure
Is this the best approach ?
I have tried iterating using $each()
Upvotes: 0
Views: 650
Reputation: 1598
try this it will give all titles with links.
$(function(){
var links = [];
$( "ul" ).find( "a" ).each(function(k,v){
links.push({ title : $(v).text(), link : $(v).attr('href'), level : $(v).parents('ul').length });
});
console.log(links);
});
Upvotes: 3
Reputation: 1198
Assuming the <ul>
you've shown above is the one inside the .thelist
block.
I think it'll be easier if you just use $(data).find(".thelist ul li")
to get all the list items inside the <ul>
element (and subelements).
Or, if you want to go down just one level, you can do $(data).find(".thelist ul>li")
.
And, you can use the following method to avoid selecting children nodes:
$("#foo")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
I got this removing children idea from here.
I hope this helps.
Upvotes: 0