Duplicate a specific html code in jquery - javascript

I have a table with some complicated values (I mean I have to make several requests to get all the values that I want in it). I need to add rows at the end of this table and fill the cells with the same code as the existing html code.
For example, I have something like :
<table id="table_cultures">
<tr>
<td>Just a string</td>
<td>Dropdown</td>
<td><div class='foo'> something..</div></td>
</tr>
</table>
<button id="plus_button" onclick="addRow()">+</button>
Now, in my javascript, I have something like :
function addRow(){
var table = document.getElementById("table_cultures"); //Get the table element
var itk = document.getElementById('foo'); //Try to get the html to duplicate
var row = table.insertRow(-1); //Add in the end of the table
var c1 = row.insertCell(0);
var c2 = row.insertCell(1);
var c3 = row.insertCell(2);
c1.innerHTML= 'Culture';
c2.innerHTML='test';
c3.innerHTML=itk;
}
So, in the variable itk, I'm trying to get the html generated and pull it into the cell, bu[Object]t it displays just HTMLFormElement (because it's a table that I want to duplicate).
Is that possible to do it that way ? Or there is an other way more simple please ?

You shall consider cloning the row node instead of getting and setting innerHTML with some thing like this:
var table = document.getElementById("table_cultures"); //Get the table element
var row = document.getElementById("rowTobeCloned"); //clone the required row
var clone = row.cloneNode(true); // copy child nodes too
table.appendChild(clone); // append the new row to the end of the table

At the moment you are not using jQuery in your code at all, but if you are looking for a jQuery solution you should try .clone()
$("#table_cultures td:last").clone().appendTo("#table_cultures tr");
JSFiddle

You using class("class='foo'") not Id ("getElementById")
so it should be something like this
function addRow(){...
var itk = document.getElementsByClassName('foo')[0]; //Try to get the html to duplicate
...}

Related

How to add something in html string

How I can add something in html string with jquery.
String html :
var stringHtml = '<td>Column 1</td><td>Column 2</td><td></td>';
I want add something in last td ( td:eq(2) ), and then append it to table.
I try:-
var stringHtml = '<td>Column 1</td><td>Column 2</td><td></td>';
$(stringHtml).find('td:last').append('<button>MyButton</button>');
$('#myTable tbody').append(stringHtml);
This script not working.
Thank you for helping.
You are appending the string, not the jQuery object.
var $ele = $('<td>Column 1</td><td>Column 2</td><td></td>');
$ele.find('td:last').append('<button>MyButton</button>');
$('#myTable tbody').append($ele);
// or $ele.appendTo('#myTable tbody');
UPDATE : The same behavior with one linear code using chaining.
$('<td>Column 1</td><td>Column 2</td><td></td>').appendTo('#myTable tbody').find('td:last').append('<button>MyButton</button>');

Using createDocumentFragment to replace an existing column in a table

I've read that createDocumentFragment is way more faster than appending elements one by one to the DOM in a for-loop, e.g. see here.
What I want to do:
Create a table column in a document fragment. This column should contain numbers from an array (for example "ratings").
After that I want to replace an existing column with the new one (the "fragment" one). So I can put the whole column to the DOM all at once.
My problem:
I can't really figure out how to replace an existing column if there already is one. Appending on the other hand is no problem.
My JSfiddle: http://jsfiddle.net/LEqG9/2/
Helpful links, here and here
HTML
<table id = "table">
<tr>
<th>Name</th>
<th>Rating</th>
</tr>
<tr>
<td>A.H.Hattray </td>
<td id = "row0"></td>
</tr>
<tr>
<td>Icke_eben </td>
<td id = "row1"></td>
</tr>
<tr>
<td>John_Doe123 </td>
<td id = "row2"></td>
</tr>
</table>
Javascript
var rating = [1, 10, 3];
var fragment = document.createDocumentFragment();
for (var i = 0, len = rating.length; i < len; i++){
var element = document.createElement('tr');
element.innerHTML = rating[i];
fragment.appendChild(element);
}
document.getElementById('table').appendChild(fragment); //I know here should be the code to replace the second column!
The following code demonstrates that it is possible to manipulate an existing table in a DocumentFragment.
var rating = [1, 10, 3];
var theTable = document.getElementById('table');
var frag = document.createDocumentFragment();
frag.appendChild(theTable);
var col2 = frag.querySelectorAll('tr td:nth-of-type(2)');
for (var i=0; i < col2.length; i++) {
col2[i].innerHTML = rating[i];
}
// it is also possible to use insertCell and deleteCell
var theRows = frag.querySelectorAll('tr');
for (var i=0; i < theRows.length; i++) {
var x = theRows[i].insertCell(1);
if (i > 0)
x.innerHTML = 'new one';
else
x.innerHTML = 'The Header';
}
document.body.appendChild(frag);
(Making the new cell in the first row a TH element, rather than TD requires a little more work, using createElement and appendChild or insertBefore.)
If you step through this the table is removed from the DOM when appended to the fragment, then reappears when the fragment is appended to the body.
Columns can't be put into the table all at once (and thus won't work as a fragment) because a column is a bunch of different cells in each of a whole bunch of rows - it's not an entity by itself.
One thing you could do for good performance is to temporarily hide the table with display: none, add all your rows/cells and then show the table again. This should allow the browser to avoid intermediate layout issues every time you add a new cell and you should only get one repaint with the final content.

question regarding javascript;Html generation and search current webpage for tags

Hi I have 3 questions, if you have for example this simple website
<html> <head> </head> <body> <table>
<tr> <td>www.hello1.com</td>
</tr> <tr> <td>www.hello2.com</td>
</tr> </table> </html>
Question 1)
If I for instance decide to click on link number 2 (www.hello2.com), Is this stored in some kind of variable?
I know that this is storing the current URL but not the one that you click
window.location.href;
Question 2)
How do you search your document, say that I would like to search the this website and store all the links in a javascript array like this
var myArray = [];
searchThisWebSiteForURLS()//Do this function that I don't know to write that search this htmlsite for url's
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com'];//This is the reslt after that the function has been executed
Question 3)
I would like to write out these links. Say that I have another table like this
<html> <head> </head> <body> <table>
<tr> <td>X</td>
</tr> <tr> <td>Y</td>
</tr> </table> </html>
Where X = http://www.hello1.com
And Y = http://www.hello2.com
Of course it shall be as many rows as there are elements in the array like this
<html> <head> </head> <body> <table>
<tr> <td>X</td></tr>
<tr> <td>Y</td></tr>
<tr> <td>Z</td></tr>
<tr> <td>A</td></tr>
<tr> <td>B</td></tr>
</table> </html>
Where Z, A, B are the elements 3,4,5 in the array
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com','http://www.hello3.com','http://www.hello4.com','http://www.hello5.com'];
EDIT!--------------------------------------------------------------------------
Wow really thanks, all of you, really thanks! I just have one more question regarding the links, when comparing two links, say that the array looks like this
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.someothersite.at'];
And say that the user has pressed the example "http://www.example.at" link, then I want to create the table containing the similar links. So I do something like this
function checkForSimilarLink(theLinkToCompareWith){// in this case theLinkToCompareWith = "http://www.example.at"
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
//Check if numLinks[i]== theLinkToCompareWith*
}
}
So how would you write this compare function? In this case we can consider
"http://www.example.at" and "http://www.example1.at" the "same" while "http://www.someothersite.at" obviosly aren't
Thanks again :)
I didn't understand question 1, but here's something for question 2 and 3:
Question 2:
var pageLinks = [];
var anchors = document.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
//now pageLinks holds all your URLs
Question 3:
// say pageLinks holds your desired URLs
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.example3.at'];
// create an empty table
var table = document.createElement('table');
// ... and it's tbody
var tbody = document.createElement('tbody');
// loop through your URLs
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
// create new table row...
var tr = document.createElement('tr');
// a cell...
var td = document.createElement('td');
// and your anchor...
var a = document.createElement('a');
// set the anchor's href
a.setAttribute('href', pageLinks[i]);
// set the anchor's text, it's also the URL in this example
a.innerHTML = pageLinks[i];
// append the anchor to the table cell
td.appendChild(a);
// ... and that cell to the new row
tr.appendChild(td);
// ... and that row to the tbody, right? ;-)
tbody.appendChild(tr);
}
// after all rows were added to the tbody,
// append tbody to the table
table.appendChild(tbody);
// and finally append this table to any existing
// element in your document, e.g. the body:
document.body.appendChild(table);
// ...or add it to a div for example:
//document.getElementById('anyDiv').appendChild(table);
Go study JQuery!!!! XDD The best for web development.
for the first and second question in with jquery:
var anchors = $('a'); //returns all <a></a> elements from here you can get the url from all of theam
With jquery u can write any element that you want.
var table = $('<table></table>');
var tr = $('<tr></tr>').appendTo(table);
var td = $('<td></td>').setText('your link here')appendTo(tr);
. . .
table.appendTo(The parent element to add the table);
Question 1:
You can capture the onclick event for clicking on the link and during that store whatever information you want to a variable of your choosing (though, this would only be relevant if you included return false in the onclick event because the link would otherwise take the user to a new page and end your session).
Question 2 and 3 were answered quite well by Alex.

Add table row before or after a table row of known ID

In a table like this:
<table>
<!-- Insert Row of bun here -->
<tr id="meat">
<td>Hamburger</td>
</tr>
<!-- Insert Row of bun here -->
</table>
function AddBefore(rowId){}
function AddAfter(rowId){}
I need to create methods without using jQuery.. I am familiar with append after and append before in jQuery.. but I am stuck with using plain js.
Use
function AddBefore(rowId){
var target = document.getElementById(rowId);
var newElement = document.createElement('tr');
target.parentNode.insertBefore(newElement, target);
return newElement;
}
function AddAfter(rowId){
var target = document.getElementById(rowId);
var newElement = document.createElement('tr');
target.parentNode.insertBefore(newElement, target.nextSibling );
return newElement;
}
You want insertBefore. Use with nextSibling to insert after a known element.

what's the easiest method to append a TR to a table by javascript?

If the table id is known – so the table can be obtained with docoument.getElementById(table_id) – how can I append a TR element to that table in the easiest way?
The TR is as follows:
<tr><td><span>something here..</span></td></tr>
The first uses DOM methods, and the second uses the non-standard but widely supprted innerHTML
var tr = document.createElement("tr");
var td = document.createElement("td");
var span = document.createElement("span");
var text = document.createTextNode("something here..");
span.appendChild(text);
td.appendChild(span);
tr.appendChild(td);
tbody.appendChild(tr);
OR
tbody.innerHTML += "<tr><td><span>something here..</span></td></tr>"
The most straightforward, standards compliant and library-independent method to insert a table row is using the insertRow method of the table object.
var tableRef = document.getElementById(tableID);
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
P.S. Works in IE6 too, though it may have some quirks at times.
Using jQuery:
$('#table_id > tbody').append('<tr><td><span>something here..</span></td></tr>');
I know some may cringe at the mention of jQuery. Including a framework to do just this one thing is probably overkill. but I rarely find that I only need to do "just one thing" with javascript. The hand-coded solution is to create each of the elements required, then add them in the proper sequence (from inner to outer) to the other elements, then finally add the new row to the table.
If you're not opposed to using jQuery, you can use either of the following where "tblId" is the id of your table and "_html" is a string representation of your table row:
$(_html).insertAfter("#tblId tr:last");
or
$("#tblId tr:last").after(_html);
i use this function to append a bunch of rows into a table. its about 100% faster then jquery for large chunks of data. the only downside is that if your rows have script tags inside of them, the scripts wont be executed on load in IE
function appendRows(node, html){
var temp = document.createElement("div");
var tbody = node.parentNode;
var nextSib = node.nextSibling;
temp.innerHTML = "<table><tbody>"+html;
var rows = temp.firstChild.firstChild.childNodes;
while(rows.length){
tbody.insertBefore(rows[0], nextSib);
}
}
where node is the row to append after, and html is the rows to append
Really simple example:
<html>
<table id = 'test'>
<tr><td>Thanks tvanfosson!</td></tr>
</table>
</html>
<script type="text/javascript" charset="utf-8">
var table = document.getElementById('test');
table.innerHTML += '<tr><td><span>something here..</span></td></tr>';
</script>
I use this, works softly:
var changeInnerHTMLOfMyCuteTbodyById = function (id_tbody, inner_html)
{
//preparing
var my_tbody = document.getElementById (id_tbody);
var my_table = my_tbody.parentNode;
my_table.removeChild (my_tbody);
//creating dom tree
var html = '<table style=\'display:none;\'><tbody id='+ id_tbody+'>' +
inner_html + '</tbody></table>';
var tmp_div = document.createElement ('div');
tmp_div.innerHTML = html;
document.body.appendChild (tmp_div);
//moving the tbody
my_table.appendChild (document.getElementById (id_tbody));
}
You can do this:
changeInnerHTMLOfMyCuteTbodyById('id_tbody', document.getElementById ('id_tbody').innerHTML + '<tr> ... </tr>');

Categories