Aravind30790
Aravind30790

Reputation: 992

Anchor tag onclick using unobtrusive javascript

<li id="Account_Tab" class="bgrad">
<a class="bganch" title="Accounts Tab" href="/xxx/xxx">Accounts</a>
</li>

there are few other <li> tags in the similar way , How can i create an onclick function for the anchor tag,

not like: <a onclick="function()"......> is there any other approach other than inline Javascript?

Upvotes: 1

Views: 1187

Answers (2)

Arun Bertil
Arun Bertil

Reputation: 4638

Try

window.onload = function(){
    var anchors = document.getElementsByClassName('bganch');

   var anchortitle= anchors.title;
};

Upvotes: 1

MrCode
MrCode

Reputation: 64526

You can add the handler like so:

function anchorClicked(){
    console.log("clicked");
}

window.onload = function(){
    var anchors = document.getElementsByClassName('bganch');

    for(var i=0; i<anchors.length; i++){
        anchors[i].onclick = anchorClicked;
    }
};

The above adds the click event to elements with the bganch class.

Other options:

  • Give the anchor an ID and use document.getElementById('someid')
  • Get all anchors by the tag name using document.getElementsByTagName('a')

Upvotes: 3

Related Questions