简体   繁体   中英

how to get child of div element

<div class="div" id="div">
    <div class="row">
        <div class="col1">
             <input type="text">
             <!--I need to get a value of these inputs-->
        </div>
        <div class="col2">
             <input type="text">
             <!--I need to get a value of these inputs-->
        </div>
    </div>
    <div class="row">
        <div class="col1">
             <input type="text">
             <!--I need to get a value of these inputs-->
        </div>
        <div class="col2">
             <input type="text">
             <!--I need to get a value of these inputs-->
        </div>
    </div>
</div>

How to get values of all of inputs in div and how to check in which div input in(col1 or col2);

in my case div with class "row" will be added via firebase database.

const inputs = document.querySelectorAll(".div > .col");
alert(inputs.value);

Using JavaScript, try looping with forEach

var inputElem = document.querySelectorAll(".row input");
inputElem.forEach(function(obj){
    console.log(obj.value)
})

Snippet:

 var inputElem = document.querySelectorAll(".row input"); inputElem.forEach(function(obj){ console.log(obj.value) }) 
 <div class="div" id="div"> <div class="row"> <div class="col1"> <input type="text" value="one"> <!--I need to get a value of these inputs--> </div> <div class="col2"> <input type="text" value="two"> <!--I need to get a value of these inputs--> </div> </div> <div class="row"> <div class="col1"> <input type="text" value="three"> <!--I need to get a value of these inputs--> </div> <div class="col2"> <input type="text" value="four"> <!--I need to get a value of these inputs--> </div> </div> </div> 

I think this could work:

$("div input").each(function(){
    // Get the value:
    console.log($(this).val());
    // check in which div input in(col1 or col2)
    console.log($(this).closest("div").attr("class"));
});

Try this:

const inputs = document.getElementById('div').getElementsByTagName('input');
console.log(inputs[0].value, inputs[1].value);

See an example here: https://jsfiddle.net/xbdd6q13/

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