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

10,311

Solution 1

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.

Solution 2

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

Share:
10,311
android.nick
Author by

android.nick

Updated on June 15, 2022

Comments

  • android.nick
    android.nick almost 2 years

    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>