Question

<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?

Was it helpful?

Solution

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')

OTHER TIPS

Try

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

   var anchortitle= anchors.title;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top