Here I have an html with javascript:
document.addEventListener('mousedown', function(event) {
let elem = event.target;
let jsonObject = {
Key: 'mousedown',
Value: event.button
};
if (event.button == 2) {
console.log(elem.outerHTML);
}
});
<span style="font-size:xx-large">
<a href="https://microsoft.com" target="_blank" rel="noreferrer noopener" shape="rect" style="color:rgb(17,85,204)">
<i>
<font color="#ff0000">Microsoft</font>
</i>
</a>
</span>
<br/>
<a href="https://google.com">Google</a>
<div>
When I right click the link, it should alert me the hyperlink inside.
The Google
works fine. But when right click Microsoft
, it always returns the font
tag.
I also tried this, still not work:
document.addEventListener('mousedown', function (event)
{
let elem = event.target;
let name = elem.tagName;
let jsonObject =
{
Key: 'mousemove',
Value: name == 'A' ? elem.outerHTML : ' '
};
if(event.button == 2 && name == 'A')
{alert(elem.outerHTML);}
});
Is there a general method for getting the links in the a
tags?
2
Answers
You can traverse the parent nodes until you find the anchor, like this:
Closest should do it