简体   繁体   中英

How to select div in javascript?

In a javascript form, I want to select a div (just one div) to apply a function for everything inside, for example, I want to select the first div and apply a function for the other div inside

 <p>Select a maintenance drone:</p> <div> <input type="radio" id="huey" name="drone" value="huey" checked> <div> <input type="radio" id="dewey" name="drone" value="dewey"> <label for="dewey">Dewey</label> </div> <label for="huey">Huey</label> </div> <div> <input type="radio" id="louie" name="drone" value="louie"> <label for="louie">Louie</label> </div>

You have many ways, by id, by class name or by query selector

 var myBox = document.getElementById("myBox"); //By id var box = document.getElementsByClassName("paper"); //By class var theBox = document.getElementsByTagName("div"); //By tag name var seleccionarId = document.querySelector("#myBox"); //By id var seleccionarClase = document.querySelector(".paper"); //By class var seleccionarElemento = document.querySelector("div"); //By tag name
 <div id="myBox" class="paper"> Im a box </div>

There are a few ways to select an element using HTML. One of the best ways is to target an element by its id. For your code, this would require adding an id to the parent div. To select an element by its id write:

let element = document.getElementById('elementID');

You can select the elements children of the element with:

element.children; //This returns an array of the children

For your specific problem, I would write:

let parentDiv = document.getElementById('parentDiv');
let children = parentDiv.children;
let childDiv = children.find(isDiv => isDiv.tagName === 'DIV'); //returns the first element that is a div

To apply a function to each element within the DIV or any other element

 const target = document.getElementById('target'); function handler(target, callback) { for (let i = 0; i < target.childNodes.length; i++) { const child = target.childNodes[i]; callback.call(child); if (child.childNodes.length) { handler(child, callback); } } } function action() { console.log('node: ', this.nodeName); } handler(target, action);
 <p>Select a maintenance drone:</p> <div id="target"> <input type="radio" id="huey" name="drone" value="huey" checked> <div> <input type="radio" id="dewey" name="drone" value="dewey"> <label for="dewey">Dewey</label> </div> <label for="huey">Huey</label> </div> <div> <input type="radio" id="louie" name="drone" value="louie"> <label for="louie">Louie</label> </div>

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