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?
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();
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With