I need to select an element within another element (a button within a form). I'd normally use jQuery; which would look something like this:
element = $('#webform-client-form-1812 input[name="op"]');
But I can't use jQuery on this project so I tried:
element = document.getElementById("webform-client-form-1812").getElementsByName("op")[0];
But I'm getting the error:
Uncaught TypeError: document.getElementById(...).getElementsByName is not a function.
This seems like one of those issues where the solution will be embarrassingly obvious to others. But I've looked at this thoroughly and I can't spot my mistake. Can someone help me?
getElementsByName
is only a method on document
- unlike getElementsByClassName
, it's not callable on individual elements.
Use querySelector
instead, and you can use the same CSS selector you used in jQuery:
const element = document.querySelector('#webform-client-form-1812 input[name="op"]');
It's probably good to use querySelector
or querySelectorAll
instead of nested getElement... getElement
calls whenever possible - it's less unnecessarily verbose and makes the code clearer. You can easily express a lot of complicated rules with a CSS selector string that would be quite unwieldy to code otherwise.
Because 'getElementsByName' and 'getElementById' can only supported by object 'document' and 'XMLDocument', you can compare with getElementByTagName. http://help.dottoro.com/ljlfpmux.php
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.