Reputation: 1
<script type="text/javascript">
function ChangeStyle()
{
document.getElementById("p1").innerHTML =
"<a href='javascript:void()' onclick=\"window.location.href='http://google.com'\">The New Link</a>";
}
</script>
<a id="p1" href="javascript:void()" onclick="ChangeStyle();alert('hello');">The Link</a>
This is the full code. For some reason the alert fires off twice. I can't figure it out.
Upvotes: 0
Views: 2155
Reputation: 221106
You probably meant to wrap your link into another element:
<span id="p1">
<a href="javascript:void()" onclick="ChangeStyle();alert('hello');">The Link</a>
</span>
Now you can replace the contents of p1
using innerHTML
the way you probably intended:
<script type="text/javascript">
function ChangeStyle()
{
document.getElementById("p1").innerHTML = "<a [...]>The New Link</a>";
}
</script>
Otherwise, you're creating a link inside of your link
Upvotes: 1
Reputation: 887767
By setting the innerHTML
of the link, you're creating another link inside of first link.
When you click on this inner link, the click event bubbles and also fires the outer click handler.
Upvotes: 5