简体   繁体   中英

How to get adjacent col value in a div-table using js?

I have an html table, which is structured like this:

<body>
<div class="block div-table" id="sidebar-record-block">
<div class="div-table-row">
  <div class="div-table-header">Sel</div>
  <div class="div-table-header">Color</div>
  <div class="div-table-header">Hex</div>
</div>
<div id="field-0000" class="div-table-row">
  <input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000">
  <div class="div-table-td">yellow</div>
  <div class="div-table-td"></div>
</div>
  <div id="field-0001" class="div-table-row">
    <input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001">
    <div class="div-table-td">red</div>
  <div class="div-table-td"></div>
</div>
</body>

I can iterate over the checkboxes using the code below and push the checked rows into an array:

saveButton.onclick = function(){
   var checkedRowIndexes = []; 
  var selectedColors = []; 
  var checkedRows = document.querySelectorAll("input[type='checkbox']");
  for (var i = 0; i < checkedRows.length; i++){
    if (checkedRows[i].checked){
    checkedRowIndexes.push(i);
    }
  }
  console.log(checkedRowIndexes);
}

But how would I go about iterating over the table and push the color (2º col) instead, using javascript ?

Thank you!

 var checkedRowIndexes = []; var selectedColors = []; var checkedRows = document.querySelectorAll("input[type='checkbox']"); for (var i = 0; i < checkedRows.length; i++) { if (checkedRows[i].checked) { checkedRowIndexes.push(i); selectedColors.push(checkedRows[i].nextElementSibling.innerText); } } console.log(checkedRowIndexes, selectedColors);
 <div class="block div-table" id="sidebar-record-block"> <div class="div-table-row"> <div class="div-table-header">Sel</div> <div class="div-table-header">Color</div> <div class="div-table-header">Hex</div> </div> <div id="field-0000" class="div-table-row"> <input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000"> <div class="div-table-td">yellow</div> <div class="div-table-td"></div> </div> <div id="field-0001" class="div-table-row"> <input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001"> <div class="div-table-td">red</div> <div class="div-table-td"></div> </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