Problem selecting element by name in practice

50 views Asked by At

I am trying use the getElementsByName() Method but it is not working for me. I cannot select the field I want. This is the page I am trying to select the email field element from. It's a booking form widget and there is an iframe involved - https://supercleaningservicelouisville.com/book-now

var iframe = document.getElementById("booking-widget-iframe");
var field = iframe.contentWindow.document.querySelector('booking[email]');

function changeCopy() {
field.placeholder = "hello";
}

document.getElementById("button").addEventListener("click", changeCopy)
<button id = "button">Click</button>

<input class="form-control input-lg ng-pristine ng-valid ng-valid-email ng-valid-maxlength ng-touched" name="booking[email]" ng-model="ctrl.booking.email" ng-change="ctrl.onBookingEmailChanged()" ng-class="{error: ctrl.booking.errors.email}" maxlength="255" placeholder="Email*" type="email" style="">

1

There are 1 answers

0
Akxe On

The getElementsByName function only accepts the name of the element, not an attribute, classes or anything else...

It then does return HTMLCollection (iterable) that is similar to an array.

The "old school" way is:

let field = Array.from(document.getElementsByName("booking")).find(el => el.hasAttribute('email'));

But much easier is to do document.querySelector('booking[email]').


On a side note...

If you use angular, use it properly and add ng-click to change property in scope, that is used as placeholder

<input placeholder="{{myPlaceHolder}}">
<button ng-click="myPlaceHolder = 'new placeholder'"></button>