3

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.

1
  • 1
    Give each link a unique id. Commented Apr 21, 2014 at 14:18

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

8 Comments

Wow this is exactly what I needed, and you got me a response in less than 2 minutes. Absolutely amazing, I've been looking around online for this answer for hours. Making an account here was a fantastic idea. Thank you so much kind stranger <3
@user3556859 - You're welcome, asking on Stack Overflow will usually get you an answer in just a few minutes, but remember to use the search function first, and to accept the answers that help you out.
Perfect! I'll make sure to do that, I did search for the answer before I posted, I'm sure its somewhere else but all of the other options on stack overflow didn't work. I'm unsure if I can ask another question in the comments but what if there is no "name" attribute? could I specify what the "href" attribute is?
Yes, you can check any attribute, but note that above we're checking a property, the element.name property, the same works for href, as in element.href, but the href property will return an absolute URL which is a "gotcha" for many newbies, so you probably have to use element.getAttribute('href'), which is how you get an attribute. Attributes and properties are not the same thing, even if they have the same value in many cases, and look like they would be the same.
I'm not sure if I did it right but I just replaced the "this.name" with "this.href" then put the absolute path to the link. Everything seems to be working exactly as I need it too. Thank you so much for your help!
|
1

You can do like in this JS Fiddle Demo , its pretty simple:

JS:

var anchorTags = document.querySelectorAll('.ClassName');
for (var i = 0; i < anchorTags.length; i++) {
    anchorTags[i].onclick = function() {
        alert(this.innerHTML);
    }
}

Hope this helps.

Comments

0

It's not very performant but you can use name selectors. .className[name=link1] however, if you have multiple links the best way to handle something like this is to use event delegation. It's really easy if you have access to jquery

I would do something like

parent.on('click', '.ClassName', function(event) {
  var button = $(this),
      name = button.attr(name);

  switch(name):
    case link1
    case link2
    ...
});

this way you don't have to assign individual events to the different links. You could also do something like this without event delegation if you really wanted to it would just be changing it to

 var links = $('.ClassName');
 links.on('click', function() {
   ...
 });

Keep in mind that the latter will attach an eventHandler to each link.

If you don't have jQuery you can still do this you just need to grab the elements differently and handle attachEvent vs addEventHandler. Also, applying the delegation will require delving into the event.currentTarget object.

something like:

var parent = document.getElementById('parentid');
parent.addEventListener('click', function(event) {
  if (event.currentTarget.getAttribute('class')indexOf('ClassName') > -1) {
    ... do stuff w/ that link here
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.