views:

39

answers:

2

Is there a very simple way to select all H2 tags on the page, then take the text in those H2 tags and add the text of each one to a list.

example:

<H2>I'm number one!</H2>
<H2>I'm number two?</H2>
<H2>I'm number three.</H2>

the script will grab those, and copy their contents into a list when the page is loaded:

<UL>
<LI>I'm number one!</LI>
<LI>I'm number two?</LI>
<LI>I'm number three.</LI>
</UL>
+5  A: 

Yes:

$('h2').each(function() {
  $('ul').append($('<li/>', {text: $(this).text()});
});

Of course you might want to tag your <ul> element with an "id" or whatever. If you don't start off with a <ul> on the page, then you'd construct it as described in a couple other answers.

Also, as Nick correctly points out, if there are a bunch of those <h2> elements then you might want to stash the jQuery handle for the <ul> element in a variable, to save the repeated lookup.

Pointy
+1 - I'd cache the UL selector though :)
Nick Craver
Yes Nick I would too :-) It's hard to type in a really polished answer fast enough around here!
Pointy
Damn it! you guys are too fast. Was posting my answer when you already answered it :(
Roberto Sebestyen
Ha ha I actually switched to using Chrome recently because I was getting so sick of Firefox getting really laggy in the "Answer" editor :-)
Pointy
It's better to use `'<li>' + foo + '</li>'` instead of your way. See this url: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly.
GuidoH
Nice link GuidoH
Matt
Yes @Guido that's a good point - again, if there are a whole bunch of `<h2>` elements it could be sluggish, so you'd want to build up the `<ul>` contents as a string and append the DOM chunk all at once.
Pointy
+1  A: 

With jQuery it's really easy:

var ul = $('<ul />');
$('h2').each(function(obj) {
    ul.append('<li>' + $(obj).html() + '</li>');
});

Now ul will contain the h2-titles. :)

GuidoH