How to access specific tr and td from a tbody without jQuery? - javascript

I'm trying to access the first tr and from it the second and third td element. However, I want to achieve this without the usage of jQuery or any other library. I already tried accessing it by using .childNodes[1] or by trying to treat it as an array. I want to know how to do this in general so I can apply it for other tables aswell (in case I want to access a different tr)
The tbody:
<tbody>
<tr role="row" class="odd">
<td>0</td>
<td>15</td>
<td>200</td>
</tr>
</tbody>

A HTMLTableElement element contains a rows property and a HtmlTableRowElement has a cells property. Both are collections.
Alternatively you can use document.querySelectorAll to retrieve (an array of) cells within the first row and subsequently retrieve the last two of those.
You can also get the targeted cells using one css query (last alternative).
const firstRow = document.querySelector(`table tbody`).rows[0];
console.log(firstRow);
const secondTdOfFirstRow = firstRow.cells[1];
console.log(secondTdOfFirstRow);
// alternative
const firstRowLastTwoCells = [...document
.querySelectorAll(`table tbody tr:nth-child(1) td`)].slice(-2);
console.log(firstRowLastTwoCells);
// another alternative
const firstRowLastTwoCellsInOneGo = document
.querySelectorAll(`table tbody tr:nth-child(1) td:not(:first-child)`);
console.log([...firstRowLastTwoCellsInOneGo])
<table>
<tbody>
<tr role="row" class="odd">
<td>0</td>
<td>15</td>
<td>200</td>
</tr>
</tbody>
</table>

Related

Select and sort a column in a table using Javascript

I want to select a particular column of a table and sort it accordingly using Javascript (No frameworks or plugins). Could anyone help me regarding this?
<table>
<thead>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
</thead>
<tbody>
<tr>
<td>Data11</td>
<td>Data23</td>
<td>Data53</td>
<td>Data45</td>
</tr>
<tr>
<td>Data81</td>
<td>Data42</td>
<td>Data33</td>
<td>Data4854</td>
</tr>
<tr>
<td>Data84681</td>
<td>Data452</td>
<td>Data354</td>
<td>Data448</td>
</tr>
<tr>
<td>Data1846</td>
<td>Data25635</td>
<td>Data3232</td>
<td>Data44378</td>
</tr>
</tbody>
</table>
function sortTableByColumn(tableId,columnNumber) { // (string,integer)
var tableElement=document.getElementById(tableId);
[].slice.call(tableElement.tBodies[0].rows).sort(function(a, b) {
return (
a.cells[columnNumber-1].textContent<b.cells[columnNumber-1].textContent?-1:
a.cells[columnNumber-1].textContent>b.cells[columnNumber-1].textContent?1:
0);
}).forEach(function(val, index) {
tableElement.tBodies[0].appendChild(val);
});
}
In your page, add id to the table tag:
<table id="myTable">
From javascript, use:
sortTableByColumn("myTable",3);
tBodies[0] is used because there can be many. In your example there is only one.
If we have var arr=[123,456,789], [].slice.call(arr) returns a copy of arr.
We're feeding it the html-rows-collection, found in tBodies[0] of tableElement.
Then, we sort that array with an inline function that compares two array elements, here: rows (<tr>).
Using cells[columnNumber] we access the <td>s, and textContent to access the text content. I've used columnNumber-1 so you can enter 3 for third column instead of 2, because the index of first element of an array (column 1) is 0...
The forEach goes through the elements of the array, which is by now in order, and appendChild row to the tBody. Because it already exist, it just moves it to the end: moving the lowest value to the end, then moving the second lowest to the (new) end, until it ends with the highest value, at the end.
I hope this is what you want. If so, enjoy!
Try using datatables you can get it from http://datatables.net its reallt easy to use. depends on jQuery
$("table").dataTable();
boom! and its done.

Get a specific column in a table

What I want is to get a specific table column using jquery, so far what I have is this, that selects the first column:
table.find(tr > td:first-child)
But I want to be able to select any column so I can copy it to another table, is there a way to do this for example :
td:n-child
so I can send it the number of column and get all the data from that specific column.
Try this:
for instance for selecting the 2nd element, you would:
table.find("tr > td:nth-child(2)");
table.find("tr > td").eq(n);
I just wrote this from the heart, so I can't confirm if it works, but I think this is the syntax to do this.
:eq() Selector : Description: Select the element at index n within the matched set.
You could use :eq() Selector, e.g :
$('tr > td:eq(n)')
Hope this helps.
$('td:eq(2)').css('background-color','green')
$('tr:eq(2) td:eq(0)').css('background-color','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr>
<td>1</td>
<td>A1</td>
<td>B1</td>
</tr>
<tr>
<td>2</td>
<td>A2</td>
<td>B2</td>
</tr>
<tr>
<td>3</td>
<td>A3</td>
<td>B3</td>
</tr>
</table>

Jquery alternate way of calling :first

I am using cheerio which is like jQuery for node.js, but :first is not available.
I want to use something like
var title = $(this).find('td:not([rowspan]):first').text();
So when I am grabbing data I can ignore all td elements that have [rowspan]. For most of the data it looks like
<tbody>
<tr>
<td>Title</td>
<td>somethingelse</td>
</tr>
<tr>
<td>Title</td>
<td>somethingelse</td>
</tr>
<tr>
<td>Title</td>
<td>somethingelse</td>
</tr>
<!-- SOMETIMES THERE IS AN UNRELATED TD IN THE FIRST -->
<tr>
<td rowspan="2" style="text-align:center; background:#ffdacc; textcolor:#000;"><b>3</b></td>
<td>Title</td>
<td>somethingelse</td>
</tr>
</tbody>
Since there are no classes I need to grab the $('td:nth-child(1)') or $('td:first') element, but in some cases its actually the second element.
Use .eq(0):
var title = $(this).find('td:not([rowspan])').eq(0).text();
You need to use the :first-child or :first-of-type and not :first:
var title = $(this).find('td:not([rowspan]):first-child').text();
var title = $(this).find('td:not([rowspan]):first-of-type').text();
If the above both doesn't work, you need to loop through to satisfy the stuff and once done, you can break.
maybe you can use .eq(0) to get the first element of the colection
$('td').eq(0)
If this is referring to the tr then you can use .first()
var title = $(this).find('td:not([rowspan])').first().text();
you can use nth-child(1)
var title = $(this).find('td:not([rowspan]):nth-child(1)').text();

Remove table row that contains a table

I have html that displays a table similar to:
<table>
<tr>
<th>col1</th>
<th>col2</ht>
</tr>
<tr>
<td>0001</td>
<td>Test</td>
</tr>
<tr>
<td colspan="2" id="detailsTable">
<table>
<tr>
<th>one</th>
<th>two</th>
</tr>
<tr>
<td>xxxxxx</td>
<td>xxxxxxx</td>
</tr>
</table>
</td>
</tr>
There is a column of expand and contract buttons on the outer table so that the nested table is only shown when the user clicks to expand.
The expansion works and the table gets displayed. However when when I try and remove the row from the outer table that contains the child table it doesn't work.
I had code like:
var rowIndex = $(this).parent().parent().prevAll().length;
$("table[id$=gvParentAccounts] tr").eq(rowIndex + 1).remove();
If the row only contains text it works as I'd like and removes the row, however if like in this case the row contains a table it is unable to remove the row as required.
I'm using ASP.Net and jQuery for this.
Thanks
Alan.
How about:
$(this).parent().parent().remove();
I'm not sure if this is exactly what you have, but here's a JSFiddle demonstrating that it works:
http://jsfiddle.net/9TQG9/1/
EDIT: Actually this:
$(this).parents("tr").eq(0).remove();
would be much nicer and more reliable. See here:
http://jsfiddle.net/9TQG9/2/

Remove all but a specific row from a table

I want to remove all rows apart from the row with id 'row0' from a table:
<table class="mytable">
<tr id="row0" class="myrow">
<td>aaa</td>
</tr>
<tr class="myrow">
<td>bbb</td>
</tr>
<tr class="myrow">
<td>ccc</td>
</tr>
</table>
But the following JQuery code removes ALL rows:
$('.mytable').children().not('#row0').remove();
Could someone explain why this happens? I would think that the child with id 'row0' would be excluded, but obviously that's not the case.
I have found another way to do this but still curious why the above method doesn't work:
$('.mytable').find('tr:not(#row0)').remove();
Because the children of a table element are thead, tfoot or tbody elements. A tbody element is always created in the generated DOM, even if it is not explicitly written in the HTML code.
You can also do:
$('.mytable tr').not('#row0').remove();
or
$('#row0').siblings().remove();

Categories