0

i am new to programming and i want to select input element of type text and name "somename".

below is the html code,

<div id="root" class="outer-div">
 <div class="settings input-div active layout final">
 <form>
 <div class="form-div"></div>
 <div class="input-with-actions">
 <input type="text" name="somename">
 <div class="actions"></div>
 </div>
 </form>
 </div>
</div>

i have tried using,

const form = document.querySelector[forms[0]);
const input_elem = form.querySelector('input');

The above selects other input on the document. i want to select the input based on the div with id root or something more accurate such that it doesnt select other input element on the page.

Could someone help me with this. thanks.

asked Nov 4, 2019 at 21:38
2
  • 1
    document.querySelector[forms[0]) - the method takes a string, not a variable. In your case, you should even be getting an error, as you're referencing the variable being declared right now. You need document.querySelector('form')[0] to select all form elements on the page and then get the first one. Commented Nov 4, 2019 at 21:40
  • It uses CSS selectors, shown here: w3schools.com/cssref/css_selectors.asp Commented Nov 4, 2019 at 21:45

1 Answer 1

2

querySelector() accepts a string, which is a selector targeting the element, a la CSS syntax.

In your case, it sounds like you want:

document.querySelector('#root input[type=text][name=somename]');

Always check the error console; you would be getting an error with:

const form = document.querySelector[forms[0]);

...even if the faulty syntax ([ rather than () were corrected.

answered Nov 4, 2019 at 21:40
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.