am trying to click this svg button however it is not working due to some code input maybe not in the right order or format.
var hangoutButton = document.getElementsByClassName("M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z");
hangoutButton.click();
html code from firefox
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="w-5 h-5 ml-auto my-4 text-gray-500 hover:text-gray-700 cursor-pointer"><path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd"></path></svg>
some image reference
enter image description here 1
2
Answers
You have to target the instance of the element for it to be triggered with the click() function. Ideally, it would be best if you’d include a unique identifier, like an id attribute for your target element, and target it with either
document.querySelector()
, ordocument.getElementById()
.The
document.getElementsByClassName()
targets the DOM elements with specified class attribute and stores them in a list. However, note that:If you intend on targeting the element using the d attribute. Then the following querySelector will do the trick:
EDIT:
"Hello World!" message is displayed once the user clicks the element. Unfortunately,
myElement.click()
function logs an error in the console:I’m not an expert on why that is, but I know alternative solution to this issue. By wrapping the <svg> element with a <button> or an <a> (anchor) tag.
Apply the onClick event to the wrapper element instead and use that wrapper as the target element for click() trigger. Here is an example:
When you write:
you get a list of object which have the mentioned class.
(Also in this case the class of SVG does not match with the one in script)
Try out this, It works for me:
Here I used the same class of SVG element and also took the first object in the list at index 0.
I tested the SVG click functionality as: