Javascript: How can I remove appended child row (tr)? - javascript

I am using JS to append array data to a table.
I am trying to add a button that removes the appended data, and puts its own data in instead. I can get the data to be added, but I cant get the data removed.
I have tried these with no luck -
.children().last().remove();
&
.removeChild() ;
I have a fiddle but I cant get the original data remove when new added (button now works! -thanks) - http://jsfiddle.net/2waZ2/37/
What code do I add so when the new line from the array is added the old data is removed?
Code to append on load:
var row = document.createElement('tr');
row.innerHTML = displayArrayAsTable(QR4, 24, 25);
document.getElementById('mytable').appendChild( row ) ;
Button code to add data:
function addNewRow() {
var row = document.createElement('tr');
row.innerHTML = displayArrayAsTable(QR4L, 24, 25);
document.getElementById('mytable').appendChild( row ) ;
}

http://jsfiddle.net/2waZ2/47/
Removing the 1st child row:
var table = document.getElementById('mytable');
table.removeChild(table.children[1])

I have updated the fiddle and it works fine now.
You can use something like this before adding the new row:
var last = document.getElementById('mytable').lastChild ;
document.getElementById('mytable').removeChild(last);

A trivial answer with jQuery: http://jsfiddle.net/guard/2waZ2/48/

Related

Tampermonkey, Chrome how to automatically insert rows into a table?

I've tried with a stupid way of inserting code for a new table, but not even that seems to work. What would be the proper way?
Here's what I tried to do:
var table = document.getElementsByClassName("test")
[0].getElementsByClassName("tableclass");
for (var i = 0, l = table.length; i < l; i++) {
var content = table[i];
let s = content.innerHTML;
s = s.replace(/table/g, 'table border="1"');
s = s.replace(/tr>[\s\S]*?<tr>[\s\S]*?<td>3/g, 'tr>\r\n<tr>\r\n<td>3');
content.innerHTML = s;
}
And a fiddle: https://jsfiddle.net/d10tk7nr/1/
Also, the reason my stupid way doesn't contain the whole table is because some of the cells where I want to eventually use this would contain random data and I don't know how to skip that.
If you want to create a new HTML-Element, every browser got you covered on that.
var tr = document.createElement('tr');
console.log(tr);
The browser console will show you exactly what you have created - a new HTML element that is not yet part of the DOM:
<tr></tr>
The same goes with the creation of some content for that table row:
var td1 = document.createElement('td'),
td2 = document.createElement('td');
td1.innerText = '5';
td2.innerText = '6';
console.log(td1, td2);
The result will be two td-elements:
<td>5</td> <td>6</td>
Now we have to glue these parts together. Browsers will also have you coverd on this:
tr.append(td1);
tr.append(td2);
console.log(tr);
The result is a complete table row:
<tr><td>5</td><td>6</td></tr>
All we have to do is append this row to your table:
var table = document.querySelector('.test table tbody');
table.append(tr);
The elements you have created are now part of the DOM - child elements of the body of your table to be excact.
Click here for a fiddle
Edit
If you want to insert the new row to a specific place, you have to find the element you that should be next to it and use insertBefore. This would change the the last piece of code to:
var targetTr = document.querySelector('.test table tr:nth-child(2)');
targetTr.parentNode.insertBefore(tr, targetTr);
If you want to choose where to put your new row within your javascript, you can use the childNodes property:
console.log(table.childNodes);
I'd use insertAdjacentHTML, like so:
table[i].insertAdjacentHTML('beforeend', '<tr><td>5</td><td>6</td></tr>');
Please see this fiddle: https://jsfiddle.net/52axLsfn/4/
Also demonstrates how to set the border. Note that this code targets all tables, so depending on your situation you may want to be more specific.

Jquery contenteditable for all cells not rows

I create a table by adding rows and columns with JS and Jquery.
This is my code:
function AddColumnToDataTable(){
$('#tableHeader').append("<th> Header </th>").attr("contenteditable", true);
// Add a new ColumnHeader and set the property "editable"
}
function AddRowToDataTable(){
var count = $('#tableHeader').find("th").length;
// Get the count of Columns in the table
var newRow = $('#tableBody').append("<tr></tr>");
// Add a new Row
for(var i = 0; i < count ; i++){
newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true);
// Fill the cells with a default text and set the property "editable"
}
}
So my question is, how can I write the code, that each cell is editable? At the moment, when I click, the whole row goes editable? Each cell should have that property.
I found a code that could help:
//$('table th:nth-child(4)').attr("contenteditable", true)
This makes the 4th header/cell editable, but how can I use it, each new created header/cell is the nth-child?
The jQuery append function doesn't return the new [appended] element, rather it returns the element that was appended to, hence the error in your code. Regardless, it's easier just to set the attribute manually in the append string. So, change this line:
newRow.find('tr').last().append("<td> Content </td>").attr("contenteditable", true);
To this:
newRow.find('tr').last().append("<td contenteditable="true"> Content </td>")
That should do it
It worked with
$('table td').last().attr("contenteditable", true);

Add class name to appended child elements with jquery

I have a table like this.
<table id='table1'>
</table>
and in this table i am dynamically adding rows to the table using jquery like below.
var tbl = $("#table1");
tbl.append('<tr></tr><tr></tr><tr></tr>');
I can add class to the appended rows using 2 methods like below
case 1
tbl.find('tr').eq(0).addClass("test");
tbl.find('tr').eq(1).addClass("test");
or case 2
for (var i=0;i<tbl.find('tr').length;i++) {
tbl.find('tr').eq(i).addClass("test")
}
and my question is there any way i can add same classname to the dynamically appended rows. Answers expecting in jquery. Thanks in advance.
Once an element is added to the DOM, you have no way of telling if it was dynamically added or not unless you have custom code that does such. I would suggest changing .append to .appendTo so you have access to the rows you're adding and can call .addClass:
var tbl = $("#table1");
$('<tr></tr><tr></tr><tr></tr>').appendTo(tbl).addClass("test")
You could also put the class in the string then append it or modify it (add a class) prior to appending it. Note how I only have one tr in my string but append it multiple times (optionally adding a class as noted)
var tbl = $("#table1");
var tr = '<tr class="test"></tr>';
var td = '<td class="test">new data</td>';
//var addedrow = $(tr).append(td).addClass("newclass");//adds class to the row
var addedrow = $(tr).append(td);//create new row object
addedrow.find('td').addClass("newclass"); //adds class to the td in the new row
var ar2 = $(tr).append(td);
var ar3 = $(tr).append(td);
tbl.append(addedrow, [ar2, ar3]); // appends the new rows
tbl.find('tr').last(td).addClass("newclass");//add class to last rows td
see it in action here: http://jsfiddle.net/MarkSchultheiss/0osLfef3/

Jquery Mobile Table Reflow

I'm trying to create my own script for a mobile version of my tables on my website.
Im currently using the script below to get the size of the table, and create new tables for each row, duplicating the headers into each new table.... (see: http://api.jquerymobile.com/table-reflow/ ) to get an idea of what I'm trying to achieve.
My script is as follows, but their is a js fiddle included at the bottom for a better example.
My problem is that I am only able to create 1 inside each table, where it should really be 3 rows, inside of each table. Again check the fiddle below for a proper example. Can anyone see why it is only creating 1 row in the table?
<script>
$(document).ready(function(){
var TableSize = $("table thead tr th").not("table.mobile_table thead tr th").size(); // Get # of columns
var i = 1;
var TableRowCount = $("table tbody tr").size(); // Get # of body rows
$("table thead tr th").each(function(){
$(this).attr("id", i++); // Give headers incrementing ID
});
for ( var CreateTables = 1; CreateTables < TableRowCount; CreateTables++ ){ // Create new table class="mobile_table" for each row
$("table").after("<table class='mobile_table'></table>");
}
$("table.mobile_table").each(function(){// Insert original headers into each row of new table as first column
var h = 1;
while ( ++h < TableSize){ // this is where the error is, it gives me the stuff below but x3 (the number of created tables)......
$("table.mobile_table").after("<tr><td></td><td></td><td></td></tr>");
}
});
console.log(TableSize);
console.log(TableRowCount);
});
</script>
See the fiddle: http://jsfiddle.net/Yf7KV/
Do you mean like this: http://jsfiddle.net/Yf7KV/2/
JS
$(this).append("<tr><td class='mobile_col_1'>Col 1</td><td class='mobile_col_2'>Col 2</td></tr>");
Explanation: Append will alllow you to append elements one after the another. html replaces with what you currently have

Deleting all the clone node of a table row in javascript

function newRow(t) {
var parent = t.parentNode.parentNode.parentNode;
var row = t.parentNode.parentNode.cloneNode(true);
row.firstChild.nextSibling.firstChild.setAttribute('value', 'sumit');
parent.appendChild(row);
}
function removeRow(t) {
var y = t.parentNode.parentNode;
y.parentNode.removeChild(y);
}
the above code is working fine but i want to delete all the clones at once which are created by above code on a onchange event of a select box
Just add a class name to the cloned elements which would allow you to search for them and delete them later:
var row = t.parentNode.parentNode.cloneNode(true);
row.className += ' clonedrow';
...
// Remove all the cloned rows
var clonedRows = document.querySelectorAll('.clonedrow');
for (var i = 0; i < clonedRows.length; i++) {
clonedRows[i].parentNode.removeChild(clonedRows[i]);
}
Once the cloned rows have been added to the DOM, they look (to JavaScript) just like the original rows.
Since you're just appending cloned rows to the table body, what I would do is as follows:
Outside the functions, as soon as the document loads, use .childNodes.length to get the number of rows in your table and store it globally in, say, lastpos.
When you need to delete the clones, start at .childNodes[lastpos] and remove nodes until the table has lastpos rows again.

Categories

Resources