2D array with getElementsByTagName? - javascript

I am trying to access table cells in javascript using the getElementsByTagName method as shown below. Ultimately I want to compare each cell in the array to another value, and be able to change the background color of that cell according to the comparison.
var cells = document.getElementById("myTable").getElementsByTagName("tr");
for (i = 0; i < cells.length; i++)
{
cells[i] = cells[i].getElementsByTagName("td");
}
However, if I try to access cells[0][0], it returns undefined. I feel like I don't fully understand getElementsByTagName is doing... is there any hope for this method? Is there a more efficient one?

use jquery it will be simple :
var contentArray = new Array();
$('tr').each(function(indexParent) {
contentArray['row'+indexParent] = new Array();
$(this).children().each(function(indexChild) {
contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
});
});

You can access any cell directly using the table element's .rows property, and the tr element's .cells property:
var myCell = myTable.rows[y].cells[x];
No need to build your own array.
So don't use .getElementsByTagName(), which returns a one-dimensional array. (Well, actually a NodeList, but you can use it like an array as long as you remember that it is live.)
If you did want to loop through all cells to compare them to some other value here's how, left to right, top to bottom using .rows and .cells:
var rows = document.getElementById("myTable").rows;
for (var y=0; y < rows.length; y++) {
for (var x=0; x < rows[y].length; x++) {
var cellAtXY = rows[y].cells[x];
cellAtXY.someProperty = something; // your code here
}
}

You need to do something like this for each row.
var row = table.getElementsByTagName('tr')[rowIndex];
var cells = row.getElementsByTagName('td');
then build your array from the contents of these variables.

Use this to get the table cells as 2D array
var tableRows = (document.getElementById("myTable")).getElementsByTagName("tr");
var cells = [];
for(var i = 0; i < tableRows.length; i++) {
cells.push(tableRows[i].getElementsByTagName("td"));
}
And now you can get any cell on your table using
cells[0][0]

Related

Javascript to Jquery for loops

I would like to convert these for loops into jQuery but I am unsure how to do this. I am also unsure of how to convert document.querySelector. I tried to convert it like this:
$('.table1 tbody')
but it does not work when you call
tablebody.row[]
This is my code:
var headertext = [],
headers = $(".table1 th"),
tablebody = document.querySelector(".table1 tbody");
for(var i = 0; i < headers.length; i++) {
var current = headers[i];
headertext.push(current.textContent.replace(/\r?\n|\r/,""));
}
for (var i = 0, row; row = tablebody.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
Thanks
You can use map() to create an array from the attributes of the specified th elements. You can then loop through that array and set the data attribute on the required td elements.
That being said, you can change the logic entirely to do this in a single each() loop. Try this:
var $headers = $('.table1 th');
$('tr > td').each(function(i) {
$(this).data('th', $headers.eq($(this).index()).text().replace(/\r?\n|\r/, ""));
});
Working example
Note that jQuery keeps data attributes in an internal cache, so you won't see any changes to the DOM with the above code (which is why in the jsFiddle example I set the text() too). This is absolutely fine, you just need to remember to use jQuery's getter signature of data() to retrieve the attribute.
For your reference, your attempt to convert querySelector to $('.table1 tbody') didn't work because the jQuery version returns a jQuery object, not a DOMElement, and jQuery object's don't have rows property.
You can use each function in jquery to iterate over elements.
$('.table1 th').each(function(index){
var text=$(this).text();
});
And
$('.table1 tbody td').each(function(index){
var tdObject=$(this);
// loop for iterating over all the TDs of table.
// You can use tdObject to get text, class and other values.
// e.g. var id = tdObject.attr('id');
var text=tdObject.text();
});

Missunderstanding append() or a treatement in Js/JQuery

I need a bit of comprehension on this one pls :
Its a function to sort by price product. Only problem is that I dont get why I dont have to empty my table before appending the products
Here is a playground
This is the code
$length = $('[data-th="Prix : "]').length;
$dispo = $('.productsDispo');
$temp = 0;
for(var i = 0; i < $length; i++)
{
for(var j = i; j < $length; j++)
{
$prixI = $($dispo[i]).find($('[data-th="Prix : "]')).text().slice(0, $($dispo[i]).find($('[data-th="Prix : "]')).text().length-2);
$prixJ = $($dispo[j]).find($('[data-th="Prix : "]')).text().slice(0, $($dispo[j]).find($('[data-th="Prix : "]')).text().length-2);
if(parseInt($prixI) < parseInt($prixJ))
{
$temp = $dispo[i];
$dispo[i] = $dispo[j];
$dispo[j] = $temp;
}
}
}
for(var i = 0; i < $length; i++)
{
$('.rwd-table tbody').append($dispo[i])
}
That's because of how append works in jQuery. From docs:
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned):
Since you do the sorting and appending manipulating the very DOM objects you selected, they are already in the table, and you basically move them inside the table with append.
jQuery's append does not make a clone of an element that you pass to it. It 'cuts' the element from its old location and 'pastes' it into a new one.
Here's a simpler example that shows this behavior, if anyone needs it illustrated.

Javascript: Traversing through array and accessing its various elements?

Essentially what I'm trying to do right now is, given some input text, I split it up by white space and display on a
div id= "animation"
Every time a button is clicked, the array should go forward one word.
This is my current attempt.
function displayText() {
var displayText = document.getElementbyID("animation");
var list = (document.getElementbyID("input").split(/[ \tn]+/);
for (var i = 0; i < list.length; i++) {
displayText.innerHTML = list.get[i];
}
}
Is my thought process somewhat correct? For whatever reason, it doesn't seem to be working.
there are multiple issues in your method
function displayText() {
var displayTextAnimation = document.getElementbyID("animation"); //keep variable name and method name different
var list = (document.getElementbyID("input").value).split(/[ \tn]+/); //use value property and observe extra bracket
for (var i = 0; i < list.length; i++) {
displayTextAnimation.innerHTML = list.charAt(i); //observe replacing get by charAt
}
}

Appending Items from one array to each and every element of another array in Javascript

Note: I am not asking how to append data to an array!
Rather my problem is that I want to append items to each and every element of an array.
Here is a part of my code:
dataset=[];
var xpoints=["Jan","Feb","Mar","Apr","May"];
var ypoints=[10,20,30,40,50];
for (var i = 0; i < xpoints.length; i++) {
dataset.push({
x : xpoints[i],
y : parseFloat(ypoints[i])
});
}
The array so far would be as below:
dataset[0] - {x:Jan,y:10}
dataset[1] - {x:Feb,y:20}
dataset[2] - {x:Mar,y:30}
dataset[3] - {x:Apr,y:40}
dataset[4] - {x:May,y:50}
So far there is no problem...
But if now i have another array (Suppose that it is of the same length), I want to append the new array's elements into my existing array such that my output would be as follows:
var zpoints=["a","b","c","d","e"];
/*
Do something
*/
Required Output:
dataset[0] - {x:Jan,y:10,z:a}
dataset[1] - {x:Feb,y:20,z:b}
dataset[2] - {x:Mar,y:30,z:c}
dataset[3] - {x:Apr,y:40,z:d}
dataset[4] - {x:May,y:50,z:e}
If I do:
for (var i = 0; i < dataset.length; i++) {
dataset.push({
z:zpoints[i]
});
}
it would append it as different elements in the dataset array, which is not what I am looking for.
Is the required output achieveable using JavaScript? How?
What if I want to add multiple objects to the dataset array but I do not know the number of objects to be added while compiling?
Suppose that there can be multiples arrays:
z1=["a","b","c","d","e"];
z2=["l","m","n","o","p"];
z3=...
.
.
and so on.. and the number is unknown until runtime.
I want to do something like this:(invalid code)
for(var j=0;j<length;j++) //Length will be known only during runtime
for (var i = 0; i < dataset.length; i++) {
dataset[i].z[j] = zpoints[i]; //z[j] is invalid!!
}
I need to name the objects dynamically somehow. Is there a way to achieve this?
It's rather simple:
for (var i = 0; i < dataset.length; i++) {
dataset[i].z = zpoints[i];
}
A .push call will always append more entries to the array; in this case you want to modify the existing ones.
You need to simply add new property z to existing object:
var l = zpoints.length;
while(l --)
dataset[l].z = zpoints[l];

Generate table based on number of rows, columns in jquery

How do I generate a table in jQuery based on a given number of rows and columns?
You can use nested for loops, create elements and append them to one another. Here's a very simple example that demonstrates creating DOM elements, and appending them.
You'll notice that the $('<tag>') syntax will create an element, and you can use the appendTo method to, well, do exactly that. Then, you can add the resulting table to the DOM.
var rows = 5; //here's your number of rows and columns
var cols = 5;
var table = $('<table><tbody>');
for(var r = 0; r < rows; r++)
{
var tr = $('<tr>');
for (var c = 0; c < cols; c++)
$('<td>some value</td>').appendTo(tr); //fill in your cells with something meaningful here
tr.appendTo(table);
}
table.appendTo('body'); //Add your resulting table to the DOM, I'm using the body tag for example

Categories

Resources