I’m trying to pass selector of the First Name field at that page: https://register.gotowebinar.com/register/4509387877809921038 to the replaceValue
function (source: Enter data into a custom-handled input field)
replaceValue('#registrant.firstName','my_name')
function replaceValue(selector, value) {
const el = document.querySelector(selector);
if (el) {
el.focus();
el.select();
if (!document.execCommand('insertText', false, value)) {
// Fallback for Firefox: just replace the value
el.value = 'new text';
}
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
}
return el;
}
But it doesn’t work for me. As I am not familiar with web technologies I am probably making some dumb mistake. Can you please help?
EDIT: I did some tests in the console as @DiegoDeVita suggested:
EDIT2: A little more testing:
Advertisement
Answer
The main problem here is that there are dot characters within the element ID which makes writing selectors more complicated.
The linked page has the following element:
<input id="registrant.firstName" />
Since the .
has a special meaning within CSS selector context. It needs to be escaped with a . The selector
#registrant.firstName
would match an element with id registrant
and class firstName
. Whereas #registrant.firstName
matches an element with id registrant.firstName
.
The reason why you’re having issues is because has a special meaning in JavaScript string context. It escapes the character that directly follows the
. If you where to log the string
"#registrant.firstName"
you would see the output #registrant.firstName
, because the escapes the
.
and is not a actual present within the string.
To correctly match the element you’ll have to escape the in the string literal.
"#registrant\.firstName"
If you where to log this string you would see the output #registrant.firstName
, because the first escapes the second
(
"\"
is a string containing a single character).