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.
1 Answer 1
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.
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 needdocument.querySelector('form')[0]to select allformelements on the page and then get the first one.