Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I need get 2 elements inside a DIV, but this element don`t have a unique identifiers, what is the appropriate selector method?


`

Click Me

`
“`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";
});`

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading