How can I find the last visible <td> in a table? - javascript

I am using a table with one row and several <td>s inside it and am using hide/show on tds. Every td has a unique id.
Is there any way to recognize the last visible td from that table?

Yes, that's pretty trivial with jQuery
$('td:visible:last')
See this fiddle

In plain Javascript, I guess it should be something like this:
var els = document.getElementsByTagname('td');
for (var i = 0 ; i < els.length ; i++)
if (els[i].style && els[i].style.display != 'none')
last = els[i];

Related

set id using setAttribute to td of last row of element

I am generating a table row which has two columns dynamically in html containing values from the database.
I want every td of the first column to have an unique id which i have done but i cant set the id to the td of last row in the table.
Here's the code to set id
<script>
var i=0;
var id=1;
while(i<100)
{
document.getElementsByTagName("td")[i].setAttribute("id", id);
i=i+2;
id=id+1;
}
</script>
Any help will be appreciated
but i cant set the id to the td of last row in the table.
You need to get to the last row in the table first.
var allRows = document.getElementsByTagName("tr");
var lastRow = allRows[allRows.length - 1];
now set Id to the first td of last row
lastRow.getElementsByTagName("td")[0].setAttribute("id" , allRows.length + 1 );
DOM Selectors are provided for a reason. :)
var tds = $('tr td:first-child');
var i=0;
$.each(tds, function(){
$(this).attr('id',i++);
});
OR
Using pure javascript
var tds = document.querySelectorAll('tr td:first-child');
var i = 0;
for(var td in tds){
tds[td].setAttribute('id',i++);
// or
//tds[td].id=(i++).toString();
};
You can use querySelectorAll to get all first td's withing given table using :first-child;
It will return NodeList which need to be convert into in an Array.
var arrTD = document.querySelectorAll("#list-notification tr td:first-child");
arrTD = Array.prototype.slice.call(arrTD);
var i =0;
arrTD.forEach(function(val,key){
val.setAttribute('id',i);
++i
})

Finding a row with a cell with a specific value

I have to mark all rows in a table (and later change the code to delete the rows).
The table structure looks like:
<table class="table table-striped table-condensed" id="buckettable">
<thead>
...cut out
</thead>
<tbody>
<tr class="success">
<td><input class="fld-bucketno" type="checkbox" name="bucket" value="158bf61f-8f66-4dee-9ff6-b9d1f6d4b840" /></td>
<td class="text-right">
<a class="bucketNo" href="/Sim/Staging/1212">1212</a>
</td>
What I am interested in is the value of the anchor in the td - second last line.
I get a json list of id's to delete. First I mark them, then change the code to delete them. That is the idea, at least. Mind me - I know a lot of programming, but Javascript is an unknown land for me ;)
My code so far is:
success: function (resp) {
var table = $('#buckettable').find('tbody')[0];
var length = resp.length;
for (var i = 0; i < length; i++) {
var bucketNo = resp[i];
var rows = table.children.length;
for (var j = 0; j < rows; j++) {
var row = table.children[j];
var bucket = row.find('.bucketNo').text();
if (bucket == bucketNo) {
alert(bucket);
}
}
}
$('#cleanup').modal('hide');
and I fail to filter the rows. I am open to any sensible other approach - hopefully it teaches me a lot.
In the above code I manage to get the row... but then the find('.bucketNo') fails with an aexception that Object # has no method find.... which I find funny because I use that on a form earlier. Pointers to documentation VERY welcome, especially in addition to an answer.
If there is a better way to do that tell me. I was told that search by ID is faster (obviously) but somehow I am not sure - should I set a coded ID (bucket-xxx, xxx being the number) on every row?
There is a much simpler way of doing this.
var targetBucketNo = 1212;
$('#buckettable a.bucketNo')
.filter(function(item) {
return item.text() == targetBuvketNo;
})
.parent()
.remove();
To explain in more detail. The following will get the anchors with the bucketNo class that are inside your #buckettable table.
$('#buckettable a.bucketNo')
Filter will filter the results for ones that have the target bucket number
.filter(function(item) {
return item.text() == targetBuvketNo;
})
Remove will remove the elements
.remove();
You can replace .remove() with .addClass('your-class-name') if you wanted to add a class instead. This would add it to the td element so you should add .parent() before addClass.
You are accessing the native Javascript children, hence find() is not a function. However you can skip around a lot of the native functions you're using by using the jQuery filter method:
var $aTag = $('#buckettable').find('tbody td a.bucketNo').filter(function() {
return $(this).text() == bucketNo
});
alert($aTag.text());
You can also loop all links with the class "bucketNo" and then look if the ID is in your array. After this get the containing TR and delete it or add a class or something:
var resp = [2323,5656]
$('a.bucketNo').each(function() {
if( resp.indexOf( parseInt($(this).text()) ) != -1 )
$(this).closest('tr').addClass('del');
});
http://jsfiddle.net/44cEt/

jQuery to select elements based on the text inside them

How to select a tag having a specific text inside it and nothing else? For example if I have the following:
<table>
<tr>
<td>Assets</td><td>Asset</td>
</tr>
<tr>
<td>Play</td><td>Players</td><td>Plays</td>
</tr>
</table>
Is there any way that I may select the <td>Asset</td> and nothing else. I tried it with contains i.e. $("table tr td:contains(Play)") but it returns all the tds in the second tr (as it should). Whereas I just want <td>Play</td>.
Is there any way to achieve this, like there's a way to select elements based on their attributes. Is there any way to select elements based on the text inside them?
How about that:
var lookup = 'Asset';
$('td:contains('+ lookup +')').filter(function() {
return $(this).text() === lookup;
});
Demo
Try before buy
Try something like this :
$("table tr td").filter(function() {
return $(this).text() === "Play";
})
If it was an input field you can specify something similar, but a little more exact with $('input[name~="Plays"]) so that it would filter out every other word, leaving the value isolated.
Other than that, the only way I know of doing this with a table is with what you had, but also throwing a conditional statement to check the text inside them.
Here is my version of accomplishing this:
http://jsfiddle.net/combizs/LD75y/3/
var play = $('table tr td:contains(Play)');
for (var i = 0, l = play.length; i < l; i++) {
if ($(play[i]).text() === "Play") {
// your script to modify below
$(play[i]).css({"color" : "red"});
}
}

JQuery Table Manipulation Inserting rows

What I want to do, in short, is from $(this) being a table row, find the next table row with a class of "example" (not necessarily a sibling).
I.E. use next() to find the next row with a class of "example" which isn't a sibling.
HTML:
<table>
<tr><td>One</td></tr>
<tr class="current"><td>Two</td></tr>
<tr><td>Three</td></tr>
<tr><td>Four</td></tr>
<tr class="target"><td>Five</td></tr>
<tr><td>Six</td></tr>
</table>
JavaScript:
var current = $('.current').next();
while(current.size() && !current.hasClass('target')) {
current = current.next();
}
current.css('color', '#0f0');
OR
$('.current').nextAll('.target').last().css('color', '#0f0');
If you're building those <tr>s from strings, you could do something like that:
var x = '';
for(var i = 0; i < 3; i++) {
x += '<li>Test ' + i + '</li>';
}
$(x).appendTo('#test');
So instead of inserting the table rows one by one, put them together as one string, make a jQuery object from that string and attach that to your table.
This also helps you with performance, since you edit the DOM only once.

Iterate over div's tables and their elements?

If I have a div res which contains N table elements with Y div's with id eye-d inside of them..
How would I iterate over these for each table getting the eye-d.innerHTML's?
NOTE: eye-d is unique. There is many tables in the 1 eye-d.
Example of eye-d
<div id=​"eye-d">​
<table border=​"0" cellpadding=​"2" cellspacing=​"1" class=​"list">​
<tbody>​
<tr class=​"table_text">​…​</tr>​
<tr>​
<td class=​"odd">​…​</td>​
<td class=​"odd">​ABC</td>​
<td class=​"odd">​N/A​</td>​
</tr>​
</tbody>​
</table>​
</div>
As requested.. rephrased...
I have 1 div with an id eye-d then I have many tables... each of these tables have many div's with class odd. I want the .innerHTML's of the odd's for each table inside eye-d.
Your id's are not unique.
You cannot have more than one <div> with an id of "eye-d".
Id's have to be unique whilst the name property does not have to be unique. You may want to use classes instead.
<div class="eye-d"> ... </div>
[[Edit]]
The selector for those div's is as simple as $("#eye-d table .odd") (uses jQuery )
If you must use raw JS then you can :
var div = document.getElementById("eye-d");
var tables = [];
recurse(res.childNodes, function(el) {
if (el.nodeName.toLowerCase() === "table") {
tables.push(el);
}
});
// array of innerHTML of odd divs.
var oddDivs = [];
for (var i = 0, ii = tables.length; i < ii; i++) {
recurse(tables[i].childNodes, function(el) {
if (el.className.indexOf("odd") > 0) {
oddDivs.push(el.innerHTML);
}
});
}
function recurse(nodeList, do) {
for (var i = 0, ii = nodeList.length; i < ii; i++) {
do(nodeList[i]);
if (nodeList[i].childNodes.length > 0) {
recurse(nodeList[i].childNodes, do);
}
}
}
Recurse recursively walks the node tree to and calls do for every element if finds. You can then search for whatever you want.
If there are Y divs and by eye-d you mean eye- followed by a *d*igit/number, then it's as easy as while (Y--) document.getElementById('eye-'+Y).innerHTML=...
As I understand it, you have:
1. A div with an ID of eye-d.
2. There are several tables inside of this div.
3. You want to get each table and view its innerHTML.
var allTables = document.getElementById('eye-d').getElementsByTagName('table');
for(i in allTables){ alert(allTables[i].innerHTML); }

Categories

Resources