Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 369
android.nick Avatar asked Aug 20 '10 14:08

android.nick


2 Answers

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.

like image 82
Pointy Avatar answered Oct 13 '22 09:10

Pointy


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

like image 34
Guido Hendriks Avatar answered Oct 13 '22 09:10

Guido Hendriks