//Trying to retrieve the HTML element from the below HTML and attempting to click on it using the Javascript code below
<html>
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>
</html>
<script>
var polygons = document.getElementsByTagName('polygon');
if(polygons.length>0)
{
//This statement doesn't work. Trying to simulate the click on the polygon element. The click function doesn't click it
polygons[0].click();
}
</script>
Contrarily to my fellow, I will purposely and kindly disregard the fact that you didn't set a click event listener, but will instead answer the question that everyone missed here.
The click
method you are trying to use is the HTMLElement.click method.
This method is available to all elements inheriting from HTMLElement, but your <polygon>
is an SVGPolygonElement, which does not inherit from HTMLElement.
So no, you can not use this method on this element, because it has no such method defined in its prototype chain.
// an SVGElement
var poly = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
// an HTMLElement
var unknown = document.createElement('foo');
console.log('<polygon> (SVG element)');
console.log('has click method:', !!poly.click);
console.log('inherits from HTMLElement:', poly instanceof HTMLElement);
console.log('//////////////////');
console.log('<foo> (HTML element)');
console.log('has click method:', !!unknown.click);
console.log('inherits from HTMLElement:', unknown instanceof HTMLElement);
But even though this method is not available, you can well trigger a click event programmatically, e.g with the EventTarget.dispatchEvent method.
var poly = document.getElementById('poly');
poly.dispatchEvent(new Event('click'));
function _log(evt) {
console.log('clicked');
}
<svg>
<polygon id="poly" points="60,20 100,40 100,80 60,100 20,80 20,40" onclick="_log()"/>
</svg>
Or since your issue seems to be related to WPT (that I really don't know), it seems that you can also do the same with the sendClick
method, but once again, I don't know WPT and I just got it from a fast-read of the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With