4

How can I handle a link which doesn't have an id? It just has a classname like "classbeauty".

Now I need to know if a user has clicked the link. If the link is clicked I just need to call alert("yes link clicked");.

I don't know how to handle events in JavaScript.

How can I do that?

1
  • 3
    Try jQuery. Take it out for a few drinks. See if you get along. No long term commitment required. Commented Apr 25, 2010 at 21:22

6 Answers 6

15

If jQuery is an option:

 $("a.classbeauty").click(function(){
   alert("yes link clicked");
 });

If you need pure JavaScript:

var elements = document.getElementsByTagName("a"); 
for(var i=0; i<elements.length; i++){
    if (elements[i].className == 'classbeauty') { 
         elements[i].onclick = function(){ 
           alert("yes link clicked!"); 
   }
 } 
}

If you need it in Greasemonkey:

function GM_wait() {
    if(typeof unsafeWindow.jQuery != 'function') { 
        window.setTimeout(wait, 100); 
    } else {         
            unsafeWindow.jQuery('a.classbeauty').click(function(){
                    alert('yes link clicked');
                }); 
    }
}
GM_wait();
Sign up to request clarification or add additional context in comments.

1 Comment

Why not getElementsByTagName("a")?
4

If you control the source code, you could add your script inline.

<a onclick="alert('yes link clicked'); return false">Link</a>

If you're targeting modern browsers, you could select the element with getElementsByClassName. Several other people here have presented their own implementations of this function.

var node = document.getElementsByClassName('classbeauty')[0]
node.onclick = function(event){
    event.preventDefault()
    alert("yes link clicked")
}

Comments

3
function getElementsByClassName(class_name) {
    var elements = document.getElementsByTagName('*');
    var found = [];

    for (var i = 0; i < elements.length; i++) {
        if (elements[i].className == class_name) {
            found.push(elements[i]);
        }
    }

    return found;
}

getElementsByClassName("YourClass")[0].onclick = function () { alert("clicked"); };

This is pure javascript, by the way. Everyone here loves jQuery (including me).

4 Comments

You can't assign onclick on an Array.
Don't forget that elements can have multiple, space-separated classes, so this solution might miss an anchor with more than one class. An easy fix is to add var regex = new RegExp("\\b" + class_name + "\\b") and then if (regex.test(elements[i].className) { instead of just checking string equality of class names.
I was trying to keep it simple but you are right, I didn't think of that, thanks!
As sad as it may be, some organizations still do not use JQuery but you can always use low-level JavaScript.
1
for (var i= document.links.length; i-->0;) {
    if (document.links[i].className==='classbeauty') {
        document.links[i].onclick= function() {
            alert('yes link clicked');
            return false; // if you want to stop the link being followed
        }
    }
}

1 Comment

+1 This is a good answer, please be correct and don't downvote!
1

I'm not sure if this is an option, but I would flip a flag when the link is clicked, and then just test for that variable.

//javascript
var _cbClicked = false;   
function checkClicked() {
    if (_cbClicked) alert("link was clicked");
    return false;
} 

//html
<a href="#" class="classbeauty" onclick="_cbClicked = true; return false;">Link Text</a>
<a href="#" onclick="checkClicked();">Check Link</a>

Very simple, and pure JS :)

Comments

0
function handleLinks(className, disableHref) {
    var links = document.body.getElementsByTagName("a");

    for (var i = 0; i < links.length; i++) {
       if (links[i].className == className) {
           links[i].onclick = function(){
               alert('test')
               if (disableHref) {
                   return false; //the link does not follow
               }
           }
       }
    }

}

handleLinks('test', true)

you can test it at this link: http://jsfiddle.net/e7rSb/

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.