如何获得div元素的孩子

时间:2018-01-21 14:54:00

标签: javascript html

<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>

如何获取div中所有输入的值以及如何检入(col1或col2)中的div输入;

在我的情况下,带有“row”类的div将通过firebase数据库添加。

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

3 个答案:

答案 0 :(得分:2)

使用JavaScript,尝试使用forEach

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

段:

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>

答案 1 :(得分:0)

我认为这可行:

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

答案 2 :(得分:0)

试试这个:

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

请在此处查看示例:https://jsfiddle.net/xbdd6q13/