Mark html element

Asked

Viewed 145 times

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 don’t know, and then I would create a summary with them, using <li> and counter in the CSS.

How could I do that?

  • One way to do this involves using jQuery. A response with jQuery would be acceptable in your case?

  • I may have misunderstood, but why don’t you give your elements a CSS class, like,: <h2 class="sumario">texto</h2> ? So they are marked and you can access them through the class .sumario.

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);
    }
}
  • That’s what I wanted :D

1

You don’t need to mark the titles.

Just build your list into a script. Follow tested code:

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 the H2 tags in your code. Take a look at the link below:

JSFIDDLE

  • 1

    You don’t even need Sizzle, you can use document.querySelectorAll

  • 2

    Or document.getElementsByTagName, if you value compatibility.

  • I think I expressed myself badly, I would like that by clicking on the H2 onClick, it stores in memory, so if I have a button, it generate the summary for me...

  • The idea would be to have N(several) H2, and only the ones I select to store in memory to then generate a list with contents of the same

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

  • In the example posted, I realized that titles only appear when you call the DIV with the id = Lista. I don’t think that’s the point of the question.

  • It’s just an example to show that JS has stored the <H2> and how it can use them, since they are in js memory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.