0

I want to open a URL when the following is clicked:

<span class="taglib-text">Forgot Password</span>

Can anybody provide me with its Javascript?

Actually, I cannot control the HTML that's why I need to call an event using Javascript and class name i.e. taglib-text

Boaz
  • 19,892
  • 8
  • 62
  • 70

1 Answers1

3

Try this:

var url = 'http://www.google.com';
var element = document.getElementsByClassName('taglib-text')[0]; // only targets the first element it finds
element.addEventListener('click',function(){
    location.href = url;
});

If you have many elements with that class you can instead use:

var url = 'http://www.google.com';
var elements = document.getElementsByClassName('taglib-text');
for (var i = 0; i < elements.length; i++){
    elements[i].addEventListener('click', function () {
        location.href = url;
    });
}

FIDDLE

I changed my answer from using .querySelector() to .getElementsByClassName() because of Shawn's comment and this test

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • why not use `document.getElementsByClassName()`? I mean, your answer is correct +1, but from what I know `.querySelector()` only pulls in a static list of elements as opposed to `.getElementsByClassName()` which pulls in a live list of elements. – Shawn G. Nov 21 '13 at 22:53
  • @ShawnGrav, good point. Edited answer. – Sergio Nov 21 '13 at 23:03
  • It does not work. Can you create an HTML example using JSFiddle? – user1980107 Nov 21 '13 at 23:15
  • @user1980107 I fixed an error in the code, he had a period in his `.getElementsByClassName()` – Shawn G. Nov 21 '13 at 23:23
  • Please help. I'm still not able to use it. – user1980107 Nov 21 '13 at 23:32
  • @Sergio, you should remove the period in `getElementsByClassName`'s string argument, as pointed out by Shawn Grav. – MasterAM Nov 21 '13 at 23:47
  • @MasterAM, thanks. Introduced a bug by changing to `.getElementsByClassName()` and then went to bed :) Corrected! – Sergio Nov 22 '13 at 06:19
  • @ShawnGrav, Introduced a bug by changing to .getElementsByClassName() and then went to bed :) Not so good... Corrected! – Sergio Nov 22 '13 at 06:20
  • 1
    @user1980107, added a fiddle example. Wrapped the code in a window.onload function, in case your problem is that you are running the javascript before your html is ready/loaded. – Sergio Nov 22 '13 at 06:24