I have the following problem - I am having difficulty creating the new TR row dynamically and then getting it to insert the data as a new table (TD) line.
The full question is as below;
Create a script that inserts a new row with the values March and £580 as the last child of the following HTML table.
<table id=”takings”>
<tr>
<td>January</td>
<td>£100</td>
</tr>
<tr>
<td>February</td>
<td>£300</td>
</tr>
// insert here
</table>
My attempt or idea was to create the TR first and then for each item in the text array add a TD within that newly created TR. However this doesn't seem to create anything.
My JS is as below;
function insertNode(newNodeTypeTD, newNodeTypeTR, newNodeTextArray, element) {
let parentElement = document.getElementById(element);
let newTR = document.createElement(newNodeTypeTR);
for (let i = 0; newNodeTextArray.length; i++) {
let newText = document.createTextNode(newNodeTextArray);
newTR.appendChild(newText);
parentElement.insertBefore(newTR, parentElement.children[i]);
}
}
window.onload = function() {
insertNode("td", "tr", ["March", "£580"], "takings")
}
Note this line: for (let i = 0; newNodeTextArray.length; i++) {
newNodeTextArray.length is 1 or greater, so this condition always returns true.
What you likely meant to do was
for (let i = 0; i < newNodeTextArray.length; i++) {
Related
I followed the example here: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces
But I have 2 things I can't figure out.
The first is how do I add a class name for all the td elements?
The second, is how do I inject this table into a div named "main",
rather than document.getElementsByTagName("body")[0];
I don't really understand the [0] at the end of the document.getElementsByTagName("body"), why is it necessary?
The first is how do I add a class name for all the td elements?The
first is how do I add a class name for all the td elements?
classList.add
The second, is how do I inject this table into a div named "main"
getElementById
I don't really understand the [0] at the end of the
document.getElementsByTagName("body")
Because getElementsByTagName is generic. It can return multiples for any tag. [0] says "give me the first", and since it's BODY, we pretty much are sure there's only one.
function start() {
// get the reference for the body
var mybody = document.getElementById("main");
// creates <table> and <tbody> elements
mytable = document.createElement("table");
mytablebody = document.createElement("tbody");
// creating all cells
for(var j = 0; j < 3; j++) {
// creates a <tr> element
mycurrent_row = document.createElement("tr");
for(var i = 0; i < 4; i++) {
// creates a <td> element
mycurrent_cell = document.createElement("td");
mycurrent_cell.classList.add("myClass");
// creates a Text Node
currenttext = document.createTextNode("cell is row " + j + ", column " + i);
// appends the Text Node we created into the cell <td>
mycurrent_cell.appendChild(currenttext);
// appends the cell <td> into the row <tr>
mycurrent_row.appendChild(mycurrent_cell);
}
// appends the row <tr> into <tbody>
mytablebody.appendChild(mycurrent_row);
}
// appends <tbody> into <table>
mytable.appendChild(mytablebody);
// appends <table> into <body>
mybody.appendChild(mytable);
// sets the border attribute of mytable to 2;
mytable.setAttribute("border","2");
}
start();
.myClass {
color:red;
}
<div id="main"></div>
I want to detect the last table row cell of a table which doesn't have any value (text).
var all_product_cell = document.getElementsByClassName("product-cell");
for (var i = 0; i < all_product_cell.length; i++) {
var td = all_product_cell[i];
alert(all_product_cell.length);
}
This code returns the table rows length... but I don't know how to check the last row which is clean and put there a message "hello!"...
UPDATE :
With this code system find last cell and put HELLO, but how I check the last cells who haven't text value and put the Hello there?
var all_local_cell = document.getElementsByClassName("product-cell");
for (var i = 0; i < all_local_cell.length; i++) {
var td = all_local_cell[i];
total_rows = all_local_cell.length-1;
all_product_cell[total_rows].value = "HELLO";
const productTable = document.querySelector(".your-product-table"); // get the table
const textOnLastCell = productTable
.rows[productTable.rows.lenght -1] // get last row
.cells[productTable.rows[productTable.rows.lenght -1].cells.lenght -1] // get last cell of last row
.innerText // get inner text
You can get last row of table by using below line :
var product_table = document.getElementsByClassName("product-cell");
console.log(product_table);
for (var i = 0; i < product_table.length; i++) {
total_rows = product_table[i].rows.length;
last_row = product_table[i].rows[total_rows-1];
last_row_length = last_row.cells.length;
last_column = last_row.cells[last_row_length-1]; // directly get last cell
If(last_column.innerHTML() == “”){
last_column.innerHTML = “Hello friend”;
}
console.log(last_column.innerHTML);
for(var j =0;j<last_row.cells.length;j++){ // you can find through loop using which cells is empty
console.log(last_row.cells[j]);
}
// console.log(last_row);
}
If you give html code will help better way.
https://codepen.io/aviboy2006/pen/ZEYBWWE
Here's a table with two empty TD'S.
The function will get an array of all TD's with the class product-cell and loop through each cell and check if innerHTML is empty, and then it will set lastTD to the last empty TD and set its innerHTML to "Hallo"
setTextLastEmptyCell()
function setTextLastEmptyCell(){
let tds = document.getElementsByClassName('product-cell')
for(let td of tds){
if(td.innerHTML === '') lastTD = td
}
lastTD.innerHTML = 'HALLO'
}
<table>
<tr>
<td class="product-cell">ABC</td>
<td class="product-cell">DEF</td>
<td class="product-cell">CBA</td>
</tr>
<tr>
<td class="product-cell"></td>
<td class="product-cell">CDA</td>
<td class="product-cell">ACB</td>
</tr>
<tr>
<td class="product-cell">ABC</td>
<td class="product-cell"></td>
<td class="product-cell">DEF</td>
</tr>
</table>
Hey i have this code:
<body>
<table>
<tr>
<td class="first">100</td>
</tr>
</table>
<h4 class=curs style="display:none">10</h4>
<script>
document.body.onload = function(){
var firstTdVal = document.getElementsByClassName('first')[0].innerHTML;
var secondTdVal = document.getElementsByClassName('curs')[0].innerHTML;
var valueToBeShown = parseInt(firstTdVal)/ parseInt(secondTdVal);
document.getElementsByClassName('first')[0].innerHTML = valueToBeShown ;
}
</script>
</body>
As you see ".first" has a number in it,this number is divied to ".curs" and the result is showed in ".first" too.Now the problem is that for exemple i add 100 more td's with class ".second,.third...,.hundred" in table.How to make script to do the same for all td's as it does for the ".first"(devide to ".curs").How do i do this in my JS by keeping it complex.
Use document.querySelectorAll to get an array of matched elements (matched with CSS selector), then loop through them using forEach, applying you logic one td at a time. Like this:
// querySelector gets the first element matched. textContent get the text of that element
var cursValue = parseInt(document.querySelector(".curs").textContent);
// querySelectorAll get an array of all the matched elements
var tds = document.querySelectorAll("td");
// loop through that array one td at a time
tds.forEach(function(td){
// get the text of the current td
var value = parseInt(td.textContent);
// if the value is not valid (a string for example) return and don't process anymore for this td (go straight to the next one).
if(isNaN(value)) return;
// calculate the new value
value = value / cursValue;
// change the text of this td (update it to the new value)
td.textContent = value;
});
NOTE: querySelector and querySelectorAll match elements using CSS selectors, so to match an element using a class the selector should be ".className", to match it using an ID: "#someID", ... All CSS selectors are accepted (even this one: "#anID>li.some-class a:not([href])").
NOTE2: tds is an array, so if you don't want to use forEach you can use a normal for loop (for(var i = 0; i < tds.length; i++) ...).
This will iterate over your table (be sure to set the table ID) (open dev console to view output but it's pretty straight forward.)
var table = document.getElementById("myTable");
for (var row of table.rows) {
for (var col of row.cells) {
console.log(col.className, col.innerHTML); //Class names and the values of the elements.
}
}
If you need anymore help please ask because I do not fully understand what you're trying to do here.
Here's a way where you put the number to be divided by in the first td, the number to divide by in the second td, and the result will be placed in the third td.
var trs = document.getElementsByTagName('tr');
for (var i = 0; i< trs.length; i++) {
var tds = trs[i].getElementsByTagName('td'),
first = tds[0].textContent,
second = tds[1].textContent,
third = tds[2],
result = (parseInt(first) / parseInt(second));
third.innerHTML = result;
}
<table>
<tr>
<td>10</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td></td>
</tr>
</table>
I am trying to delete multiple columns from html table using javascript.
The logic it is using is that it searches in top row for tag "" and then deletes that column.
The problem is if only one cell in top row is having '', then it deletes that columns fine, but if there are multiple columns it throws error.
Here is my code
<!DOCTYPE html>
<html>
<body>
<table style="width:100%" border='1' id='Just_for_california'>
<tr>
<td><span></span></td>
<td>S</td>
<td><span></span></td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</body>
<script>
var dataTable_length = document.getElementById('Just_for_california').rows[0].cells.length;
var count_rows = document.getElementById('Just_for_california').rows.length;
var column_array = [];
for(var i=0; i<dataTable_length; i++)
{
var str = document.getElementById("Just_for_california").rows[0].cells[i].innerHTML;
if(str.search("<span></span>") != -1)
{
column_array.push(i);
}
}
var len = column_array.length;
for(var i=count_rows-1 ; i>=0;i--)
{
rows_number = document.getElementById('Just_for_california').rows[i];
console.log("row_number:"+i);
for(var j=0; j<len;j++)
{
rows_number.deleteCell(column_array[j]);
}
}
</script>
</html>
It happens because you calculate indexes incorrectly when you delete cells. I refactored you code (making it clearer) and it seems to work now:
var table = document.getElementById('Just_for_california'),
rows = table.rows;
for (var i = 0; i < rows[0].cells.length; i++) {
var str = rows[0].cells[i].innerHTML;
if (str.search("<span></span>") != -1) {
for (var j = 0; j < rows.length; j++) {
rows[j].deleteCell(i);
}
}
}
The problem is that you are trying to remove cells "horizontally" in the row. So say you want to delete cells at indexes 1 and 3 and there are 4 columns in the table. When you delete the first cell 1 it works fine. However then you move to the right and try to remove cell at index 3. This fails because since you have already removed cell 1, there is no cell with index 3 anymore. The maximum index now is 2. Hence the error.
In my improved code I'm removing columns "vertically", so such an issue can't happen.
Demo: http://jsfiddle.net/t2q60aag/
I have the following table generated by a cgi script:
<table>
<tr id='vfipbb'><td>col 1,0</td><td>col 1,1</td></tr>
<tr id='vfipbb.alipbb'><td>col 2,0</td><td>col 2,1</td></tr>
<tr id='vfipbb.esipbb'><td>col 3,0</td><td>col 3,1</td></tr>
<tr id='vfipbb.esipbb.esipbb_madrid'><td>col 4,0</td><td>col 4,1</td></tr>
<tr id='vfipbb.esipbb.esipbb_barcelona'><td>col 5,0</td><td>col 5,1</td></tr>
</table>
This is just a sample of what it would look like, but the important bit to note is the id.
when the webpage first loads all rows are collapsed except for the root context (vfipbb). I want to enable functionality when the root context is clicked it will expand all child rows listed under this, for example (alipbb), (esipbb) and if one of the child rows is clicked it will expand all grandchildren rows, for example (esipbb_madrid) (esipbb_barcelona).
Is there any efficient way of doing this in javascript based on ID? Any pointer in the right direction would be greatly welcome!
Not a working code, but something to get you started
// add click handlers to all tr
var tr0 = document.getElementsByTagName("tr");
for (var i = 0; i < tr0.length; i++) {
tr0[i].addEventListener("click", openChild);
}
function openChild() {
var id = this.id;
//regex that matches a string beginning with
//the id followed by dot and some other words
var regex = new RegExp("^" + id + ".[a-z_]+$", "g");
var tr1 = document.getElementsByTagName("tr");
//browse through the tr(s)
for (var i = 0; i < tr1.length; i++) {
//Learn regex test function!
if (regex.test(tr1[i].id)) //if a match found
//display children
document.getElementById(tr1[i].id).style.visibility = "visible";
}
}