简体   繁体   中英

Get number of elements in a page

Let's say you have 5 <divs> with stuff in them but all have some content. So it's like:

<div class='module-class' id='module-1'>Hello world. <button class='delete'>X</button></div>
<div class='module-class' id='module-2'>Testing <button class='delete'>X</button></div>
<div class='module-class' id='module-3'>This is text <button class='delete'>X</button></div>
<div class='module-class' id='module-4'>Moon and Sun <button class='delete'>X</button></div>

Let's say you click inside the <button> that has This is text . So, obviously, it's 3rd in the page. So you would get back "Clicked on 'module-3'`

How would you do that?

$('.module-class').click(function(e){
    console.log("Clicked on '" + $(this).attr('id') + "'");
});

You can do this without jQuery as well.

(function() {
    try {
      var _divs = document.getElementsByTagName('div');
    } catch(e) {
      console.log("_divs returned undefined");
      return;
    }
    Array.prototype.forEach.call(_divs, function(el) {
        el.addEventListener('click', function() {
            console.log('div#' + this.id + ' was clicked');
        });
    });
})();

http://jsfiddle.net/V98kE/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM