簡體   English   中英

如何獲得div元素的子元素

[英]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>

如何獲取div中所有輸入的值以及如何在in(col1或col2)中檢查哪個div輸入;

在我的情況下,類“行”的div將通過firebase數據庫添加。

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

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

我認為這可能有效:

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

嘗試這個:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM