DOM - append in table - javascript

How can I add rows <tr> in to a table a any level(Top/Bottom/In between) using Javascript/jQuery ?

$(html).insertBefore($('table tr').eq(index));
Will insert some html before the tr with index specified.
A small demo

to append to the bottom:
you have nothing to do, because you just have to find the parent element and then append it.
to append to the top:
well, it is more complicated, but I think is possible. One way is following:
find the parent element from the rows and read all rows into an extra variable. Fortunatly the result will be an array of object. Then create a new row element and use the method unshift() to put this at the begin of the array. Clean table's body and then add each element to body again.

http://api.jquery.com/prepend/

Related

Find Value from certain class (HTML)

I am looking to script a site that has a set of changing values. I am trying to figure out how to call the text value inside of only one of these entries at a time.
Any one of these can look like this
<tr ng-repeat="(key, game) in crash.games.slice().reverse()" class="" style="">
<td ng-if="::game.crash > 199" class="crashHighResult">RANDOM NUMBER THAT I WANT TO SEE</td>
tr is the parent of td and the text value inside of td is what I'm trying to see
The only problem I'm experiencing is that there are as many as 20 entries stored during this time and they can all have seemingly the same classes and parents as every other one, the only difference being the random number value...
I am thinking that If I can pull them all at the same time and then maybe create an array with those values I might be able to do what I need to do but I'm a bit stumped.
I am very new to javascript and jquery and this is a learning experience for me. Thanks for your help!
Your best bet would be to use document.querySelectorAll if you want to understand some native JS techniques. There are a couple of other ways of getting the elements you want (getElementsByClassName and getElementsByTagName) but they don't play nearly as well with forEach as does the former.
So, to grab the elements:
let cells = document.querySelectorAll('td');
And to loop over that nodelist:
cells.forEach(function (cell) {
console.log(cell.textContent);
});
At the moment the code just logs the text content (your random number) to the console, but you can get a feel for what you can now do with that data.
For example, to get the last (most recent?) random number (the last cell in the nodelist) you would use:
let rnd = cells[cells.length - 1].textContent;
Hope this helps you out.
If you need to select the first tr td in the table to get the value, using jQuery you can select all tr td elements and then specify the first one.
$("tr td").first().text();
This selector finds all tr td elements as it traverses the dom, so it will find the top row in the table first. The first() function returns a jquery object of the first element found. The text() gets whatever text is inside the td tags, basically the same as the js innertext or textcontent.
If you want to do processing with all the values you can use the jquery selector each() function.
$("tr td").each(function (index , element) {console.log($(element).text())})
This loops through all the elements and prints their values to the console, but you could modify the function to sum the values, put them in an array, or whatever.

Targeting the last PARENT table-row (tr), not the CHILD table-row (tr)

I'm attempting to target the last parent table row within a table that has children table-row elements inside of it. I've tried the below jQuery to target the :last pseudo, however, like expected, it is targeting the absolute last table-row element within the targets parent table.
$('table[id*="dgRegistrantList"]').find('tr:last').addClass('EventRegLastAttendee')
I've put together a jsFiddle with the HTML block I'm attempting to target with the jQuery, I hope it is helpful!
http://jsfiddle.net/jodriscoll/LZA7e/
The Green table-row is the one I would like to target, however, the one highlighted in Red is the obvious one receiving the class.
This system can generate a variant of table rows depending on the users selection prior to this "Step". For a full example of what I'm working with, visit: http://secure.massgeneral.org/event-form (I'm working with Step 2).
Please be aware that the HTML I'm working with is produced by a CMS software that I as the customer, do not have access to changing. Hence the purpose of this jQuery exercise.
If all the parent <tr> elements have the classes BBListOddRowStyle or BBListEvenRowStyle you can do this:
$('table[id*="dgRegistrantList"]').find('tr[class*=RowStyle]:last')
.addClass('EventRegLastAttendee')
DEMO
If not, you can use .children() twice to make sure you target the right ones:
$('table[id*="dgRegistrantList"]').children('tbody')
.children('tr:last').addClass('EventRegLastAttendee')
DEMO
Use this code to target the last row:
$('table[id*="dgRegistrantList"]').find('tr[class^=BBList][class$=RowStyle]:last').addClass('EventRegLastAttendee')
Explanation:
tr //it will look for tr
[class^=BBList] //which class starts with BBList
[class$=RowStyle] //and ends with RowStyle (so we're leaving Odd and Even inside and not recognized)
:last //the last of those element, if you remove it you select all of them
Is .children() what you're looking to do?
$('table[id*="dgRegistrantList"]').children('tr:last').addClass('EventRegLastAttendee');
.children() only goes down one dom level, while .find() will go down as far as it can.
Don't use find. It will look at any depth and it may match unintended subtables. Perhaps it will work for your example, but you don't want to be acquiring a bad habit. Plus, find will be more costly than a targeted approach.
You want a more targeted approach:
var targetTd = $('table[id*="dgRegistrantList"]').children('tbody').children('tr:last').find('table:first').children('tbody').children('td:last');
use this code to target parent tr last row
$('table[id*="dgRegistrantList"]').find('tr[class^=BBList]:last').addClass('EventRegLastAttendee');

Assign and retrieve an html table to a javascript variable with jQuery

I want to backup an html table to afterwards filter it using jquery:
$('.row').closest('td').not(':contains(' + v + ')').parent('tr').remove();
Since I do remove() I have to back up the rows before:
var allTable = $('#mytable').html();
And then, when filter is performed I turn back to previous table data:
$('#mytable').html($(allTable));
But this does not work. If I do:
alert($(allTable).filter('tr').length);
next to the first assignment, zero rows are returned.
Please, can you assist me?
filter() is used to find elements within an array of elements. This isn't what you need. You're looking to find() the child elements within another. Also, storing the HTML only to turn it back in to a jQuery object is a little redundant - you may as well just store the jQuery object itself. Try this:
var $table = $('#mytable');
$table.remove(); // use your existing logic here
alert($table.find('tr').length);
$table.appendTo('body'); // add the table back in to the DOM when conditions are met
Example fiddle
I ran into a similar issue when using a highlight function. I solved it by cloning the table into a hidden div and restoring it from there, instead of from a variable. see jquery highlight() breaking in dynamic table
Did you solve this problem?
I suggest a workaround.
Instead of using your cloned table, make a (temporary) copy of it and use it for alert.
var alertTable = allTable;
alert($(alertTable).filter('tr').length);

Updating only one cell of a table

I created a 3x3 table. Each column is generated using a function. The function basically returns a "td" element. Else where in the code I trigger an event based on some conditions. Whenever the event is triggered, I want to update one particular cell of the table. None of the cells have ids attached to them.
My question is how can I link up the "td" that I want to be updated with the event?
I have no specific context that refers to this td alone.
If you're not using any other tools like jQuery my approach might be to find the table which I assume you can do with Javascript. Then for each td element in the table inject a class to them that is unique. You could just give them numbers or something easy. Assuming the numbering never changes you now have an easy way to lookup the td elements later in your code without having to keep a reference to the td element you want.
Instead of adding a class you could just get all the td elements in the table and if you knew the 4th element was always the cell you wanted then you could just keep a reference to that td element.
Without using jQuery or anything, you can use DOM selectors such as .childNodes (and iterating till you're satisfied), .lastChild, .firstChild, .parentNode etc.
This link gets you through some examples.
Although, if you are using this a lot, create ID dynamically in JS. Like iterating once through all your table (with .childNodes), assigning an ID (like row1-col2) to every td. It will simplify the rest of your code.
Here is a jsFiddle to show you how with jQuery:
http://jsfiddle.net/HzBFE/

find immediate tr elements of table element using jquery find()

I am trying to find all tr elements inside a table element. The table element it self has other table elements nested inside its rows. So when I do the following:
$(tbl).find('tr').hover(...);
...it picks up tr elements inside the nested table elements also. I just want the immediate tr elements of the table element I am trying to query.
$(tbl).find('>tr').hover(...); didn't work for me!
ps: tbl is a table element, not a string
Read full answer, please.
$(tbl).children()
will give you tbody and also thead if it exists.
So if you want immediate tr, you will need to try this.
$(tbl).children('tbody').children('tr')
Don't forget to considertbody while fetching children of a table, as in Firefox a direct call to children like $(tbl).children() returns tbody and not tr, even if its not in your markup. Complex but useful.
Happy Coding.
$(tbl).children('tr').hover(...);
This should work:
$(tbl).children('tr').hover(...);
Form the JQuery docu:
The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.
Don't forget that - even if your markup doesn't include them - from a DOM point of view, tr elements are nested inside a tbody element, so you will need to include this in the selector.
Try something like...
$(tbl).find('tbody>tr').hover(...);
Although this will probably find the nested table's tbody too, so you'll probably need something like...
$(tbl).children().find('tr').hover(...);

Categories