Javascript onclick for class and name

javascript, onclick

Solution

Attach an event handler to the elements, and just check the name and do whatever you'd like

var elems = document.querySelectorAll('.ClassName');

for (var i=elems.length; i--;) {
    elems[i].addEventListener('click', fn, false);
}

function fn() {
    if ( this.name == 'link1' ) {

        console.log('This is link1');

    } else if ( this.name == 'link2' ) {

        console.log('This is link2');

    }
}

FIDDLE

Problem

I'm new to JavaScript and am unsure how to do the following: I've got two links with the same css "class" but different "name" attributes. I need to perform different functions to each one individually when clicked using unobtrusive Javascript. Is there anyway to do this? Example code: ``` <a class="ClassName" name="link1">Link 1</a> <a class="ClassName" name="link2">Link 2</a> ``` Lets say I need to output "This is link 1" to the console when I click link 1. And "this is link 2" when Link 2 is clicked.

Original source