I am trying to convert this: Select table row and check checkbox using JQuery
into normal javascript, since I'm in a situation where I cannot use jquery.
Here is the orignal
$("table tr").each(function () {
if ($(this).find("td:eq(1)").text().trim() == '2013-03-21') {
$(this).find("input[type=checkbox]").attr("checked", true);
}
});
This is what I have so far, and I'm sure its way off:
var elements = [].slice.call(document.querySelectorAll("table tr"));
Array.prototype.forEach(elements, function(){
var tdText = this.querySelectorAll("td").textContent
if (tdText == '2013-03-21') {
this.querySelectorAll("input[type=checkbox]").setAttribute("checked", true);
}
});
This is the original table:
<table>
<tr>
<td>Record1</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record2</td>
<td>2013-03-22</td>
<td>
<input type="checkbox" />
</td>
</tr>
<tr>
<td>Record3</td>
<td>2013-03-21</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>
querySelectorAll()
returns a nodeList of elements.
You need to iterate those and deal with each instance or use the index you want like:
element.querySelectorAll("td")[0]
The code var tdText = this.querySelectorAll("td").textContent
will return an undefined textContent because you are referring to the tr
's NodeList
. You can loop through it and then you can get the td
's content:
let rows = Array.prototype.slice.call(document.querySelectorAll('table tr'));
let textDate = '2013-03-21';
rows.map((row) => {
let cells = Array.prototype.slice.call(row.querySelectorAll('td'));
for (let i = 0, length = cells.length; i < length; i++) {
if (cells[i].textContent === textDate) {
let cb = row.querySelectorAll('input[type=checkbox]');
cb[0].checked = true;
return;
}
}
});
ElemCollection.forEach.call
instead of using Array#slice.call
as HTMLCollection
does not have forEach
method [1]
index while selecting text from td
element this
in Array#forEach
does not refer to element
, use first
argument of Array#forEach
callback function which is item
of array
Array.prototype.forEach.call(document.querySelectorAll("table tr"), function(elem) { var tdText = elem.querySelectorAll("td")[1].textContent; if (tdText === '2013-03-21') { elem.querySelector("input[type=checkbox]").setAttribute("checked", true); } });
<table> <tr> <td>Record1</td> <td>2013-03-21</td> <td> <input type="checkbox" /> </td> </tr> <tr> <td>Record2</td> <td>2013-03-22</td> <td> <input type="checkbox" /> </td> </tr> <tr> <td>Record3</td> <td>2013-03-21</td> <td> <input type="checkbox" /> </td> </tr> </table>
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.