By Googlebot


2012-06-18 00:21:30 8 Comments

Consider a simple JS event of

document.getElementsByClassName('test')[0].onclick=function(){
document.getElementsByClassName('test')[0].innerHTML = 'New Text';
}

How can I extend this code to generally work for all elements with class="test". I mean getting the element clicked and replace its content. In fact, we need to get the node number (provided inside the bracket) from the click event.

I am trying to better understand javascript in unobtrusive codes, not a practical method like jQuery.

3 comments

@Blender 2012-06-18 00:26:58

Just iterate over them:

var elements = document.getElementsByClassName('test');

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', (function(i) {
        return function() {
            this.innerHTML = 'New Text';
        };
    })(i), false);
}​

I used (function(i) { return function() { ... }; })(i) instead of just function() { ... } because if you happen to use i in the callback, the value of i will be elements.length - 1 by the time you call it. To fix it, you must shadow i and make it essentially pass by value.

@Camilo Martin 2013-06-16 20:48:42

I wonder if it wouldn't be better to define the function once, and just add its reference in each iteration of the loop. I'm not sure if the browser is smart enough, but it may be creating one anonymous function each iteration.

@Danilo Valente 2012-06-18 00:24:37

var all = document.getElementsByClassName('test');
for(var i=0;i<all.length;i++)
    all[i].onclick=function(){
        this.innerHTML = 'New Text';
    }

But it's most recommended to use addEventListener (or attachEvent, in IE/Some versions of Opera, I guess):

var all = document.getElementsByClassName('test');
for(var i=0;i<all.length;i++)
    all[i].addEventListener('click',function(){//If you're gonna use attachEvent, use 'onclick' instead of 'click'
        this.innerHTML = 'New Text';
    }});

@gabeio 2012-06-18 00:27:10

He is asking how to do this for all of the elements with the class name 'test' and how to get in javascript the element [i] which was clicked. Not just to set the innerHTML to 'New Text'

@Niet the Dark Absol 2012-06-18 00:24:56

Just use this inside the function. this will be the element on which the event is being fired.

(function() {
    var elms = document.getElementsByClassName("test"),
        l = elms.length, i;
    for( i=0; i<l; i++) {
        (function(i) {
            elms[i].onclick = function() {
                this.innerHTML = "New Text";
            };
        })(i);
    }
})();

It's a bit more complicated than jQuery's:

$(".test").click(function() {
    $(this).html("New Text");
});

But it'll be significantly faster without the bloat that jQuery adds ;)

@Googlebot 2012-06-18 01:55:38

@Derek this is an interesting point! but why? addEventListerner does not overwrite previous events, but it is not supported in IE<9. Is there any advantage that I missed?

@Niet the Dark Absol 2012-06-18 02:08:15

onclick is perfectly fine, provided you understand the limitation it comes with: If you overwrite it, you lose any existing attached event.

@Derek 朕會功夫 2012-06-18 02:33:02

@Ali Well, you can always use attachEvent in IE9< , or jQuery.

Related Questions

Sponsored Content

89 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6155321 View
  • 7682 Score
  • 89 Answer
  • Tags:   javascript arrays

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

49 Answered Questions

[SOLVED] How do I get the current date in JavaScript?

  • 2009-10-07 11:39:02
  • Suresh Chaganti
  • 2508684 View
  • 2169 Score
  • 49 Answer
  • Tags:   javascript date

21 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2723610 View
  • 2886 Score
  • 21 Answer
  • Tags:   javascript url

55 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

23 Answered Questions

[SOLVED] Event binding on dynamically created elements?

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

Sponsored Content