0

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?

0

1 Answer 1

2

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');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.