Dónal
Dónal

Reputation: 187369

insert checkbox at the beginning of table cell

I want to insert a checkbox before the content of the first cell in each row of a HTML table using jQuery. I tried the following:

$("table td:first-child").each(function() {
    $(this).append('<input type="checkbox" class="basic-kpi-row"/>');
});

This almost works, it insert the checkbox into the correct cells, but the checkbox appears after the content instead of before it.

Upvotes: 2

Views: 2130

Answers (5)

rakeshjain
rakeshjain

Reputation: 1761

You need to use prepend instead of append as append will add the element at the end while prepend will add the element before all other elements in the td

Also there is no need to use each, you can use just the below:

$("table td:first-child").prepend('<input type="checkbox" class="basic-kpi-row"/>');

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388396

you need to us prepend instead of append also, there is no need to use .each() here

$("table td:first-child").prepend('<input type="checkbox" class="basic-kpi-row"/>');

Demo: Fiddle

Upvotes: 1

rahularyansharma
rahularyansharma

Reputation: 10775

$("table td:first-child").each(function() {
    $(this).prepend('<input type="checkbox" class="basic-kpi-row"/>');
});

JS FIDDLE LINK

Upvotes: 1

Rituraj ratan
Rituraj ratan

Reputation: 10378

$("table td:first-child").each(function() {
    $(this).prepend('<input type="checkbox" class="basic-kpi-row"/>');
});

reference prepend

Upvotes: 1

Lasar
Lasar

Reputation: 5437

append() adds to the end. You want prepend(), which will add your new elements right before any existing content.

Upvotes: 2

Related Questions