Thanks Liam and Ollie. Liam, a variation of your solution worked for me, and also covered all of the fancier cases I mentioned (including extracting the text from multiple HTML elements inside an LI). Nice. I was hoping there was a simple solution. Ollie, thanks for your feedback, too. I didn't get around to trying it, since the more basic solution did the trick. Here's what I ended up with:

       var str;
       $('#categoryList li').each(function(){
           str = $(this).text().replace(/\s+/g,'');
           // do something with str
       });

The regex gets rid of whitespace (line breaks, tabs and such) that come from how the HTML is laid out physically inside the LI's. In my case, it was fine to replace *all* whitespace in the text. For a case where only tabs and linebreaks should get yanked a different regex would be needed.

Thanks again!

- Jack

Liam Byrne wrote:

If it's just the text you want, I can't see why the following wouldn't work:

$('#myList li').each(function(){
 text = $(this).text();
 // do something using the text
});


Jack Killpatrick wrote:

Hi All,

Wondering if anyone can help me out with this...

I have a list like this and want to select the "innermost" text from each LI:

<li>Item One</li>
<li><a href="yadda">Item Two</a></li>
<li><div class="something"><a href="ya">Item Three</a></div></li>
<li><a href="ya">Item Four</a></li>
<li>Item Five</li>

I want to be able to perform an operation using each result (the results being "Item One", "Item Two", "Item Three", "Item Four", "Item Five"). If the LI's all have an <a> tag inside of them, I've found that this works:

var text;
$('#myList li').each(function(){
  text = $('*',this).html();
  // do something using the text
});

But that only works for cases Two and Four in my example above (not the cases where the text is bare inside the LI or there's an additional wrapper in the LI. I'm thinking I'll need to do something recursively using the content of each LI or maybe there are some existing jquery selectors that can do what I'm looking for.

Any ideas?

Oh, if this got a little more fancy (or was easier to do), if we had a case like this, it would get only the "first" text it came across ("Item Six"):

<li>Item Six<div class="something"><a href="ya">Some text</a></div></li>

Thanks,
Jack







Reply via email to