I need get 2 elements inside a DIV, but this element don`t have a unique identifiers, what is the appropriate selector method?
const buttonElem = document
.getElementById(wrapper)
.element.getElementsByTagName("button");
const inputElem = document
.getElementById(wrapper)
.element.getElementsByTagName("input");
buttonElem.addEventListener('click', () => {
const oldText = inputElem.value;
return inputElem.value = oldText === "ON" ? "OFF" : "ON";
});
<div id="wrapper">
<input type="text" value="OFF" readonly/>
<button type="button">Click Me</button>
</div>
CodePudding user response:
One option is to get the parent div
and then use querySelector
to get the child you want.
const containerElem = document.getElementById('wrapper');
const buttonElem = containerElem.querySelector('button');
const inputElem = containerElem.querySelector('input');
buttonElem.addEventListener('click', () => {
const oldText = inputElem.value;
inputElem.value = oldText === "ON" ? "OFF" : "ON";
});
<div id="wrapper">
<input type="text" value="OFF" readonly/>
<button type="button">Click Me</button>
</div>
CodePudding user response:
const buttonElem = document.querySelector('#wrapper button'); const inputElem = document.querySelector('#wrapper input');