Adding a new cell to an already existing row - javascript

I am new to javascript and I am trying to insert a new cell using only DOM properties and methods into an already existing row without hard-coding or using an index. I am trying to add a new tag. The cell needs to go first because I am adding in formation about that corresponds to that row. Any help would be appreciated. So far I have the following:
var firstTable = document.getElementsByTagName("music
header").nextChild();
console.log(firstTable);
var findRow = firstTable.getElementsByTagName("td");
console.log(findRow);
<div id = "music">
<h2 id = "music header">Music</h2>
<table style="width:100%">
<tr id = "Hard Rock">
<td>NEW CELL HERE</td>
<td>Saint Asonia</td>
<td>Shinedown</td>
<td>Breaking Benjamin</td>
<td>Rise Against</td>
<td>Three Days Grace</td>
</tr>
<tr id = "Metal">
<td>Bullet for my Valentine</td>
<td>Metallica</td>
<td>Korn</td>
<td>Asking Alexandria</td>
<td>Alexisonfire</td>
</tr>
<tr id = "Country">
<td>Toby Kieth</td>
<td>Keith Urban</td>
<td>Taylor Swift</td>
<td>Kenny Chesney</td>
<td>Miranda Lambert</td>
</tr>
</table>
</div>

The code:
var firstTable = document.getElementsByTagName("music
header").nextChild();
console.log(firstTable);
isn't going to work because:
getElementsByTagName expects a tag name, not an ID
getElementsByTagName returns a (possibly empty) collection, not a single element, and that collection doesn't have a nextChild method.
nextChild is not a valid property of any standard DOM object, perhaps you want nextElementSibling, which is a property, not a method
The id "music header" is invalid as the ID attribute value can't contain white space.
To find the first table in the document, you can use:
var firstTable = document.getElementsByTagName('table')[0];
To get the first row of the table, you can use:
var firstRow = firstTable.rows[0];
The index for rows can be any value from 0 to firstTable.rows.length - 1.
To get the first cell of the row:
var firstCell = firstRow.cells[0];
What you do next is up to you…

Since you have the parent element and you've found the first child you can try:
parent.insertBefore(el, parent.firstChild);
Here is the link to the .insertBefore docs on MDN
and here is the docs for firstChild on MDN

It's difficult to know from your question exactly what it is you're trying to achieve. That said, building on Sgnl and RobG's answers and the points the latter made about your structure and references, here is some food for thought.
I assume you want to find the table within a section. You can do that by finding the section first by the id, and then the table beneath that:
var firstTable = document.getElementById("music").getElementsByTagName("table")[0];
Your HTML example implies you then want to add a cell to the first row. You can find that row within the previously found table as so:
var findRow = firstTable.rows[0];
Now that we've found our insert location, let's construct our new cell
var newCell = document.createElement("td");
var newTag = document.createElement("span");
var newText = document.createTextNode("NEW CELL HERE");
newCell.appendChild( newTag );
newTag.appendChild( newText );
With the node built, let's insert it
findRow.insertBefore( newCell, findRow.childNodes[0] );
Here is a working JS Fiddle demonstration

Related

the DOM doesn't work with me when I try to sort an element

here is the file I have. when I try to sort some number it doesn't change and keeps empty
HTML file
<tr>
<th>Original array</th>
<td id ="td1">1,5,7,-1,3</td></tr>
<tr>
<th>Sorted Array</th>
<td id="td2"></td>
JS file
var OriginalArr = document.getElementById("td1").value;
var a = document.getElementById("td2").value;
a.value = Original.sort();
There are two main problems with this. First of all, most elements do not have a value property, only the elements that take input. You seem to be looking for textContent in this context.
Another thing is that when you get the text in td1 it must be converted to an array before you can sort it.
Here is the code with the mentioned problems fixed:
// Get text in td1
var td1Text = document.getElementById("td1").textContent;
// Get array of numbers from text
var OriginalArray = td1Text.split(",").map(function(num){
return parseInt(num,10);
});
// Get td2
var td2 = document.getElementById("td2");
// Set td2 to sorted array converted to string
td2.textContent = OriginalArray.sort().toString();
<table>
<tr>
<th>Original array</th>
<td id ="td1">1,5,7,-1,3</td></tr>
<tr>
<th>Sorted Array</th>
<td id="td2"></td></tr>
</table>
One more thing to note is that the <tr> tags must be in a <table> in order to be properly queried by getElementById. Without the table tag, getElementById returns null.

Create row in html table which does not have id and class

I would like to create one additional row in HTML Table which is very common and can be done if we have id or class available of that table.
But in my case I have one page which contains many forms and tables.
But in all those I have one form which contains only one element i.e table and I would like to create one more row and move few columns from 1st row to newly created row.
For this I have created simple HTML page.Please find below code and help me to achieve my output.
<h:form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</h:form>
Here Ia m getting output like
Item Info Description Product Keywords Documents Image Video
But I want to achieve something like below:
Item Info Description Product Keywords
NEW CELL1 Documents Image Video
means I would like to remove few columns from existing row and I would like to add it in newly created row.
For this I have written Javascript like:
<script type="text/javascript">
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.elements[0];
var tr = document.createElement("tr");
tr.id="row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
var col5 = document.getElementById("col5");
tr.appendChild(col5);
var col6 = document.getElementById("col6");
tr.appendChild(col6);
var col7 = document.getElementById("col7");
tr.appendChild(col7);
}
</script>
Here, My problem is this entire form will be generated automatically so I can't give the Id for the table and with this script it is not identifying my table when I am giving form.elemets[0];
I want to find table element so that I can create row in that table.
You can find the table by doing this:
Get one of the elements in a table row, and get the parent node until you've got the table. In this case you could do document.getElementById('col1').parentNode.parentNode
And just to ease things,
You can insert this string '</tr><tr>' in a row, after a table cell, to easily create a new row.
This should be better than document.getElementsByTagName('table'), because if you have lots of tables which are far away, it will take more time to find your table's index in that array.
Use getElementsByTagName to get the table from within your form, which has an ID
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.getElementsByTagName("table")[0];
var tr = document.createElement("tr");
tr.id = "row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
/*Your original code produces duplicate IDs which is a BAD thing*/
var col5 = document.getElementById("col5");
/*Update new Id*/
col5.id += "_new";
tr.appendChild(col5);
var col6 = document.getElementById("col6");
/*Update new Id*/
col6.id += "_new";
tr.appendChild(col6);
var col7 = document.getElementById("col7");
/*Update new Id*/
col7.id += "_new";
tr.appendChild(col7);
}
<form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</form>
You also have a mismatch of column numbers, with the code provided you originally have 7 columns and only insert 4, this will produce inconsistent results, make sure to use the colspan attribute as needed.
You should be able to use JavaScript's querySelector method to select the table data you want to remove from the document.
Something like var rowToDeleteOrAddTo = document.querySelector("#myForm > table > tr > td"); should help you get there. You'll need to lookup CSS Selectors to get the specific selectors you need. You may need to use the textContent property once you have a node to make sure you are deleting the right one.

Getting the cell of a <tr> that has particular className

What i'm trying to do is to get the cell of this where the classname is "revision_id".
<tr>
<td class="supplierOrderId">10790</td>
<td class="revision_id">#7</td>
<td class="supplier">DGI Developpement </td>
<td class="quantity">80</td>
<td class="stock">0</td>
<td class="purchase_price">10.00</td>
<td class="comments"> </td>
</tr>
I managed to do it this way :
revision = this.parentNode.parentNode;
revisionId = revision.cells[1].innerHTML.replace( /[^\d.]/g, '' );
(cause I wanna get the int of the string)
iRevisionId = parseInt(revisionId);
Is there a more proper way to do it, with the given className ?
Because in the case where someone adds a cell before mine in the future, my code is going to be "deprecated".
Hope i've given all the details,
Thanks by advance.
// More Details //
The problem with most answers is that they work only if I have 1 <tr>. Once I get multiple, it gets every revisionID like this :
console.log(result) -> #1#2#3#4
(if I have 4 <tr> for exemple)
So this is why I am getting the GOOD one like this :
revision = this.parentNode.parentNode; // outputs the good <tr>
but after that, I can't get the with the given className.
if this is tr
var data = $(this).children(".revision_id").text()
Using the text() method, you can get the text inside your td element.
After that just parse it like you did with parseInt()
$(function() {
var quantity = $('tr td.quantity').text();
console.log(parseInt(quantity));
});
you can do via jquery like this:
var value= parseInt($(".vision_id").text().match(/[0-9]+/g)[0]);
FIDDLE EXAMPLE
Depends on whether you can use jQuery or not.
Pure JavaScript
With pure JS, provided you're using a modern browser, you can use the getElementsByClassName function. For the purpose of this demonstration, I've assumed you have an ID on your table you can use.
var myClassName = 'revision_id';
var table = document.getElementById('mytable');
// the desired TD
var td = table.getElementsByClassName( myClassName ) );
See Mozilla's docs on getElementsByClassName.
Also, this answer works with backwards compatibility.
jQuery
Of course, this becomes easier with jQuery:
var $td = $('#mytable td.revision_id');
Demo here: http://jsfiddle.net/uJB2y/1/
Well if you want it with jquery then you can use .filter() method:
var text = $('td').filter(function () {
return this.className === 'revision_id';
}).text().slice(1);
text = +text; // conversion for int
alert(text);
Demo

How to make a table with rows that can be copied (adding a new row after that one, containing the same) with Javascript?

I am trying to make a table containing several rows, each with a button in the last cell that creates a copy of the row.
All the other cells contains an input (text).
The content (value) of the inputs that are added must be the same as the one above (the one they are copies of).
The copies cannot be copied however!
The inputs must have a unique name something like this:
1-1-name
1-1-age
1-1-country
1-1-email
and if this row is copied, the copied inputs must have names like this
1-2-name
1-2-age
1-2-country
1-2-email
The next one with 3 instead of 2, and so on.
The problem with this, I guess, is that I must do this without JQuery. I can only use Javascript. Is this even possible?
Take a look at this fiddle. Here is a pure js (no-jQuery) way to duplicate a table row and increment it's ID:
var idInit;
var table = document.getElementById('theTable');
table.addEventListener('click', duplicateRow); // Make the table listen to "Click" events
function duplicateRow(e){
if(e.target.type == "button"){ // "If a button was clicked"
var row = e.target.parentElement.parentElement; // Get the row
var newRow = row.cloneNode(true); // Clone the row
incrementId(newRow); // Increment the row's ID
var cells = newRow.cells;
for(var i = 0; i < cells.length; i++){
incrementId(cells[i]); // Increment the cells' IDs
}
insertAfter(row, newRow); // Insert the row at the right position
idInit++;
}
}
function incrementId(elem){
idParts = elem.id.split('-'); // Cut up the element's ID to get the second part.
idInit ? idParts[1] = idInit + 1 : idInit = idParts[1]++; // Increment the ID, and set a temp variable to keep track of the id's.
elem.id = idParts.join('-'); // Set the new id to the element.
}
function insertAfter(after, newNode){
after.parentNode.insertBefore(newNode, after.nextSibling);
}​
<table id="theTable">
<tr id="1-1">
<td id="1-1-name"><input type="text"/></td>
<td id="1-1-age"><input type="text"/></td>
<td id="1-1-country"><input type="text"/></td>
<td id="1-1-email"><input type="text"/></td>
<td id="1-1-button"><input type="button" value="Copy"/></td>
</tr>
</table>​
Edit: Updated to insert the new row after the clicked one. Now with buttons and inputs!
Yes this is possible,
you should create a new table row ,
then set its innerHTML to the innerHTML of the row above.
jQuery is a JavaScript library, which means it is built with JavaScript functions.
So everything you can do with jQuery, you can do with JavaScript too.
Léon

JavaScript DOM not being read in html table

I produce an int from JSON data
var f_page = ["TheHouseofMarley"];
retrieveData(f_page[0]);
function retrieveData(teamName) {
var baseURL = 'http://graph.facebook.com/';
$.getJSON(baseURL+teamName+"&callback=?", function(data) {
$('#FBlikes').append(data.likes)
});
};
and this works, it gives ~ 8407
I have a chart that reads data from < table id="chartData">
Grabbing the data from the table
I use a jQuery selector — $('#chartData td') — to select all the data cells in the table. I can then iterate through these cells with the jQuery each() method. For each cell, I determine if it's a label (e.g. "SuperWidget") or a value (e.g. "FBLike") cell, based on whether it's in the left or right column. I then store the cell contents under the 'label' or 'value' key in an associative array, which we then place inside the chartData array.
$('#chartData td').each( function() {
currentCell++;
if ( currentCell % 2 != 0 ) {
currentRow++;
chartData[currentRow] = [];
chartData[currentRow]['label'] = $(this).text();
} else {
var value = parseFloat($(this).text());
totalValue += value;
value = value.toFixed(2);
chartData[currentRow]['value'] = value;
}
// Store the slice index in this cell, and attach a click handler to it
$(this).data( 'slice', currentRow );
$(this).click( handleTableClick );
The problem is when I insert this number into < table id="chartData"> it is not read by the chart!
<table id="chartData">
<tr style="color: #0DA068">
<td>Number of Likes </td><td><span id='FBlikes'></span> </td> //Not Read!
</tr>
<tr style="color: #194E9C">
<td>MegaWidget</td><td>20000</td> //This is Read by the Chart!
</tr>
In short: Javascript output is not being read from HTML table.
Could anyone point me in some direction? I'm really new at code.
Usually this problem occurs in Ajax.
Build a string appending "data.likes" to it. Then finally assign the string to the element.
This may sound absolutely stupid, but it worked for me. Whenever i use to build a table dynamically in jQuery using the ajax response string, i would never get a table. Then i followed the procedure I mentioned.
If my solution works, some one please help me understand why is it so.

Categories