android.nick
android.nick

Reputation: 11215

Jquery: Select all H2 tags on page, copy the text of those H2 tags to a list

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>

Upvotes: 5

Views: 12160

Answers (2)

Guido Hendriks
Guido Hendriks

Reputation: 5776

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. :)

Upvotes: 1

Pointy
Pointy

Reputation: 413846

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.

Upvotes: 9

Related Questions