'How to Click a Button by Name in Browser Console

I am trying to click a button on a web page using the developer tools console in Google Chrome.

The HTML for the button is:

<input value="Send an Email" class="btn" name="email" onclick="navigateToUrl('/_ui/core/email/author/EmailAuthor?p2_lkid=00QU0000008xZYi&amp;rtype=00Q&amp;retURL=%2F00QU0000008xZYi','RELATED_LIST','email');" title="Send an Email" type="button">

As you can see, the button does not have an id attribute, so I'm trying to select it using the name attribute. My JavaScript code is:

document.getElementsByName("email").click()

What am I doing wrong?



Solution 1:[1]

document.getElementsByName returns an array (technically a NodeList), so you have to specify the element you want like:

document.getElementsByName("email")[0].click()

Solution 2:[2]

It's been well answered that the issue relies on the fact that document.getElementsByName() returns a node list, not a single element.

Just to point an alternative, no list return method:

If you want to browse for a single element, and do not have an id, but needs to look for any attribute (not just name), you could call it using document.querySelector(), that uses a css-like selector, and returns the first matched element, so:

var element = document.querySelector("[name='email']");

Solution 3:[3]

Elements = plural = node List

You need to select the first one.

document.getElementsByName("email")[0].click()

Solution 4:[4]

I used this to help me with an ajax function call, using the delete button. I wanted to delete an individual numbered record from the database.

$(document).on('click', "[name='delete_button']", function(){
   ajax_function();
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 j08691
Solution 2 LcSalazar
Solution 3 epascarello
Solution 4 Spinstaz