Children () only the choice of the first child
Given the following unordered list:
<ul class="nb"> <li class="home"><a href="index.html" class="current"><span class="displace">Home</span></a></li> <li class="products"><a href="products.html" title="Products"><span class="displace">Products</span></a></li> <li class="services"><a href="services.html" title="Services"><span class="displace">Services</span></a></li> <li class="support"><a href="support.html" title="Support"><span class="displace">Support</span></a></li> <li class="company"><a href="company.html" title="Company"><span class="displace">Company</span></a></li> <li class="contact"><a href="contact.html" title="Contact"><span class="displace">Contact</span></a></li> </ul> Can you tell me why the following selects only the first element of the list:
var status = 'closed'; $('ul.nb li a').click(function(e){ e.preventDefault(); if ($status == 'closed'){ var li = $(this).closest('li'); var items = li.parent().children(); console.log(items.html()); } }); The expected results are the selection of all elements of the list, the display of consoles <a href="index.html" class="current"><span class="displace">Home</span></a>
TIA
+4
3 answers
html , since getter returns the html content of the first selected item, items in your code is an array consisting of jQuery of all the selected li elements. http://jsfiddle.net/MKUGv/
+7
Because .html() does not go through every element of the jQuery object and does not concatenate all their html values. It returns only one html value.
Since li are all children, you have to sort through them yourself. Sort of:
var html = ''; items.each(function(i, elm) { html += $(elm).html(); }); +1