简体   繁体   中英

Pure Javascript insert text into <input type=“text”> without attributes

 <div style="top: 0px; left: 0px;" class="uiInlineBlock uiMenuHolder"> <div> <input type="text"> </div> </div> 

To select the input element i have used:

inputelement = document.getElementsByClassName('uiInlineBlock uiMenuHolder')[0].children[0].children[0];

The problem is i am trying to put text inside the text area but by using value i set the value but the text field remains empty. How can i fix this with pure javascript?

You may use the querySelectorAll and a cascading selectors to select the first div so the second and finally the input instead to select step by step starting from the external div:

  • div.uiInlineBlock.uiMenuHolder select the first div
  • div select the child div
  • input[type=text] select the child input text field

So the full string 'div.uiInlineBlock.uiMenuHolder div input[type=text]' will select all input text fields inside a div contained in a div having the following two classes: uiInlineBlock uiMenuHolder.

Because the querySelectorAll will return a list and because in your case you have only one input you need to take the first element of the result.

 window.onload=function() { var inputEle = document.querySelectorAll('div.uiInlineBlock.uiMenuHolder div input[type=text]'); inputEle[0].value = 'your value'; } 
 <div style="top: 0px; left: 0px;" class="uiInlineBlock uiMenuHolder"> <div> <input type="text"> </div> </div> 

 inputelement = document.getElementsByClassName('uiInlineBlock uiMenuHolder')[0].children[0].children[0] inputelement.value = 'your value'; 
 <div style="top: 0px; left: 0px;" class="uiInlineBlock uiMenuHolder"> <div> <input type="text"> </div> </div> 

More safely

inputelement = document.querySelector('.uiInlineBlock.iMenuHolder input');

inputelement.value = 'your value';

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM