Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add an onclick event to html tags without id's using javascript?

Tags:

javascript

I tried doing this but it didn't seem to work:

 window.onload = initAll;


    function initAll(){
    document.getElementsByTagName('a').onclick = clickHandler;
     }

    function clickHandler(){
        if(this.toString().indexOf("localhost") < 0) {
            confirmation = confirm("You are now leaving http://soso.com.  Please click 'ok' to continue to this site, or 'cancel' to stay in http://soso.com");
                if (confirmation == false){
                    return false;
                }

        }

    }

I know I can getElementById and that works, but it doesnt work this way. Any help would be appreciated.

Thanks!

like image 479
Graham Avatar asked Sep 13 '10 21:09

Graham


People also ask

How do you pass an event onclick in HTML?

To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .

How can I trigger a click event in JavaScript?

click() The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event.

How do you add a click event to a button with plain JavaScript?

To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.

What can I use instead of onclick in HTML?

You should use addEventListener() instead."


2 Answers

document.getElementsByTagName('a') returns a NodeList of DOM Elements. So for starters, you will have to iterate over them and attach a handler to each like this :

var links = document.getElementsByTagName('a');
for( var i=0,il = links.length; i< il; i ++ ){
 links[i].onclick = clickHandler;
}

If there are many elements, I suggest you read about event delegation and assign just one handler for everything.

like image 106
Rajat Avatar answered Oct 06 '22 01:10

Rajat


function initAll() 
{
    var elements = document.getElementsByTagName('a'); // returns an array

    // add the handler to each element
    var n;
    for (n = 0; n < elements.length; ++n)
        elements[n].onclick = clickHandler;
}
like image 41
egrunin Avatar answered Oct 06 '22 03:10

egrunin