I'm addicted to jQuery and am having trouble using pure JavaScript to loop through every <td> on a page and inserting an <input>. Can anyone help me out with this simple task?
1 Answer
If you like jQuery then you should find querySelectorAll method fun to use to select DOM elements. You can try something like this to insert input into every td on a page:
var tds = document.querySelectorAll('td');
Array.prototype.slice.call(tds).forEach(function(td) {
var input = document.createElement('input');
input.type = 'text';
td.appendChild(input);
});
<table>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
</tr>
</table>
Of course instead of fancy forEach you can use old-good for loop:
for (var i = 0; i < tds.length; i++) {
// ...
}
And instead of querySelectorAll('td') there is also
var tds = document.getElementsByTagName('td');