Ankit Rustagi
Ankit Rustagi

Reputation: 5637

Call onclick event of some other tag

I need to call the onclick event of one tag when some other hyperlink is clicked.

<div class="a"><a href=".." onclick=".?." >   // tag1
</div>
<span class="b"><a href=".." onclick="echo('hi');" >   // tag2
</span>

Thus whenever onclick event of tag1 gets executed, it should do nothing but call the onclick event of tag 2. How do i do this? (Sorry, new to Javascript).

Upvotes: 0

Views: 1223

Answers (3)

Shawn31313
Shawn31313

Reputation: 6052

document.getElementsByClassName("a")[0].onclick = function () {
    document.getElementsByClassName("b")[0].children[0].click();
}

That should do it.

You can also use (i fixed your HTML as well. Missing </a>):

<div class="a"><a href=".." onclick="document.getElementsByClassName('b')[0].children[0].click();">Link Text</a></div> <!-- Tag 1 -->
<span class="b"><a href=".." onclick="alert('Hi')">Link 2 Text</a></span> <!-- Tag 2 -->

Upvotes: 3

Rajesh Hegde
Rajesh Hegde

Reputation: 2822

Just write a javascript function. And attach it to onClick handler.

<div class="a"><a href=".." onclick="someName()" >   // tag1
</div>
<span class="b"><a href=".." onclick="someName()" >   // tag2
</span>

<script>
  function someName(){
       alert("Hi");
}
</script>

Upvotes: 0

abhinsit
abhinsit

Reputation: 3272

According to your question you want to call the same functions onclick of tag 1 and tag 2, so to put it simple you can assign same onclick function to both tags.

<div class="a"><a href=".." onclick="myFunction()" >   // tag1
</div>
<span class="b"><a href=".." onclick="myFunction()" >   // tag2
</span>

Or if you want to call it some other way like if there is some inline action provided on tag2 and you want to call it from tag 1 you can use:-

<div class="a"><a href=".." onclick="$('.b').click()" >   // tag1
</div>
<span class="b"><a href=".." onclick="echo('hi');" >   // tag2
</span>

Upvotes: -1

Related Questions