Mark html element

1

I have my elements in a text.

<h2> Titulo </h2>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do 
<h2> OUTRO TITULO </h2>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do 
<h2> OUTRO TITULO </h2>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do 

And I would like to mark the h2 elements in memory, I do not know, so I can create a summary with them, using <li> and counter in CSS.

How could I do this?

    
asked by anonymous 06.03.2014 / 16:00

3 answers

1

An example, without JQuery, where H2 elements are stored in an array, when pressed, and displayed in a list when the button is pressed.

JSFiddle

var headers = document.getElementsByTagName('h2');
for (var i = 0; i < headers.length; i++) {
    headers[i].onclick = armazena;
}

var titulos = [];

function armazena() {
    titulos.push(this);
}

function mostra() {
    var lista = document.getElementById('lista');
    lista.innerHTML = '';
    for (var i = 0; i < titulos.length; i++) {
        var el = document.createElement('li');
        el.innerHTML = titulos[i].innerHTML;
        lista.appendChild(el);
    }
}
    
08.03.2014 / 02:05
1

You do not need to mark the titles.

Just mount your list in a script. Here is the code tested:

var headings = Sizzle('h2');

for( var i = 0; i < headings.length; i++ ) {
    document.write('<ul>');
    document.write('<li>' + headings[i].innerHTML + '</li>');
    document.write('</ul>');
}

The code looks for all 'h2' tags in your code. Take a look at the link below:

  

JSFIDDLE

    
06.03.2014 / 16:11
0

If you want to store in an array to work with them dynamically, you can use this:

jQuery(document).ready(function(){
    var data = [];
    $('h2').each(function(){
        data.push($(this));
    })
});

JSFiddle

    
06.03.2014 / 16:14