简体   繁体   English

如何仅使用 javascript 从 innerHTML 中选择一个元素

[英]How to select an element from the innerHTML using javascript only

I have the following HTML table, I need to iterate through the rows and its columns.我有以下 HTML 表格,我需要遍历行及其列。

<table id="hosts" border="1">
<tbody>
   <tr>
      <td><input type="checkbox" checked=""></td>
      <td>127.0.0.1</td>
      <td>localhost</td>
   </tr>
   <tr>
      <td><input type="checkbox"></td>
      <td>255.255.255.255</td>
      <td>broadcasthost</td>
   </tr>
</tbody>
</table>


<script>
    let table = document.getElementById("hosts");
    for (let row of table.rows) {
      for (let cell of row.cells) {
        if (cell.cellIndex === 0) {
          // I need to to know if the input inside the cell is checked or not
          // I can get the cell.InnerHTML, but how do I check if the checkbox is checked or not?
        }
    } 
</script>

I dont use Jquery我不使用 Jquery

You don't want innerHTML for this, you just want to access the HTMLInputElement within that cell.您不需要为此使用innerHTML ,您只想访问该单元格中的HTMLInputElement

You can do it like this, but it's fragile:你可以这样做,但它很脆弱:

cell.firstChild.checked

I'd probably use querySelector to find the first input within the cell:我可能会使用querySelector来查找单元格中的第一个input

cell.querySelector("input").checked

Similarly, I probably wouldn't use cellIndex === 0 , so I could change the layout without breaking my code.同样,我可能不会使用cellIndex === 0 ,因此我可以在不破坏代码的情况下更改布局。 So for instance:例如:

let table = document.getElementById("hosts");
for (let row of table.rows) {
  for (let cell of row.cells) {
    const checkbox = cell.querySelector("input[type=checkbox]");
    if (checkbox && checkbox.checked) {
      // ...this cell has a checked checkbox in it...
    }
}

Side note:边注:

Beware, the HTMLCollection returned by rows and cells is not defined as being iterable, but you're relying on it being iterable by using for-of .请注意, rowscells返回的HTMLCollection未定义为可迭代的,但您依赖于它可以通过使用for-of进行迭代。 Some browsers make it iterable even though it isn't specified, but others don't.一些浏览器使它可迭代,即使它没有指定,但其他浏览器没有。

If you're doing this in a page or application (not a library), you can ensure that HTMLCollection is iterable by polyfilling it like this:如果您在页面或应用程序(而不是库)中执行此操作,则可以通过像这样填充 HTMLCollection 来确保HTMLCollection是可迭代的:

if (typeof HTMLCollection !== "undefined" && HTMLCollection.prototype && !HTMLCollection.prototype.forEach) {
    // Yes, there's really no need for `Object.defineProperty` here
    HTMLCollection.prototype.forEach = Array.prototype.forEach;
    if (typeof Symbol !== "undefined" && Symbol.iterator && !HTMLCollection.prototype[Symbol.iterator]) {
        Object.defineProperty(HTMLCollection.prototype, Symbol.iterator, {
            value: Array.prototype[Symbol.itereator],
            writable: true,
            configurable: true
        });
    }
}

See this answer doing that for NodeList (which is defined as iterable) for details.有关详细信息,请参阅为NodeList (定义可迭代)执行此操作的答案

Alternately, use querySelectorAll on the table and rows instead:或者,改为在表和行上使用querySelectorAll

for (let row of table.querySelectorAll("tr")) {
  for (let cell of row.querySelectorAll("td")) {
    // ...
  }
}

You can use querySelectorAll and querySelector您可以使用querySelectorAllquerySelector

[...document.getElementById("hosts")querySelectorAll('tr')]

This snippet is getting all the tr and converting to array so that array methods can be used此代码段正在获取所有tr并转换为array ,以便可以使用数组方法

forEach(function(item) {
  let getInput = item.querySelector('input[type="checkbox"]')

forEach is an array method and during each iteration item will tr and from it get the first input[type="checkbox"] . forEach是一个数组方法,在每次迭代期间, itemtr并从中获取第一个input[type="checkbox"] querySelector will return the first matched element. querySelector将返回第一个匹配的元素。

Then use checked to validate the state of the input然后使用checked来验证输入的状态

 let table = [...document.getElementById("hosts").querySelectorAll('tr') ].forEach(function(item) { let getInput = item.querySelector('input[type="checkbox"]'); if (getInput.checked) { console.log('checked') } else { console.log('not checked') } })
 <table id="hosts" border="1"> <tbody> <tr> <td><input type="checkbox" checked=""></td> <td>127.0.0.1</td> <td>localhost</td> </tr> <tr> <td><input type="checkbox"></td> <td>255.255.255.255</td> <td>broadcasthost</td> </tr> </tbody> </table>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用javascript设置另一个文件中元素的innerHTML? - How to set the innerHTML of an element from another file using javascript? Javascript InnerHtml 来自<select> - Javascript InnerHtml from <select> 如何在 JavaScript 中的 select 元素使用 innerHtml 在代码中稍后添加的查询选择器? - How to select element in JavaScript with queryselector which are added later in the code using innerHtml? 使用`innerHTML`是用`type`属性在JavaScript中创建`button`元素的唯一方法吗? - Is using `innerHTML` the only way to create a `button` element in JavaScript with the `type` attribute? 如何选择特定值/内部HTML <td> 在一定范围内 <tr> ? 仅使用Javascript。 没有jQuery - How to select value/innerHTML of a certain <td> within a certain <tr>? Using Javascript only. No jQuery 如何从HTML发送信息 <input> 元素<span>使用JavaScript .innerHTML?</span> - How to send information from HTML <input> element to <span> using JavaScript .innerHTML? 如何在javascript中获取此元素的innerHTML? - How to get innerHTML of this element in javascript? 如何使用javascript仅选择一个li元素? - How to select only one li element using javascript? 如何仅使用Javascript在div中显示整个select元素 - How to show an entire select element in a div using only Javascript 如果仅使用javascript,如果另一个div为空,如何将innerHTML添加到div - How to add innerHTML to div if another div is empty only using javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM