This question already has answers here:
Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?
(2 answers)
Closed 3 months ago.
I want to use jQuery to create a table. Currently I have an empty table body and I would like to use some jQuery to fill up the table:
var $tr = $("<tr>"),
$td = $("<td>");
var date = '2018-01-01'
$td.text(date);
$tr.append($td);
$td.text("New Years");
$tr.append($td);
$("#body").append($tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
<table>
But this only appends the second td. The first one gets overwritten. Any ideas on how to fix?
Like Taplar said in comments, if the element already is in DOM, the .append will only "move it".
Now in your example, you append it a the same place, but also change the text.
Try the .clone() method to duplicate elements.
var $tr = $("<tr>");
var $td = $("<td>");
var date = '2018-01-01';
$td.text(date);
$tr.append($td);
var secondCell = $td.clone().text("New Years");
$tr.append(secondCell);
$("#body").append($tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
</table>
var $tr1 = $("<tr>"),
$tr2 = $("<tr>"),
$tr3 = $("<tr>"),
$td = $("<td>");
var date = '2018-01-01';
$td.text(date);
//various ways to accomplish it
$tr1.append($td.prop('outerHTML'));
$tr2.append($td.clone());
$tr3.append($('<td>', { text: date }));
$td.text("New Years");
$tr1.append($td.prop('outerHTML'));
$tr2.append($td.clone());
$tr3.append($('<td>', { text: 'New Years' }));
$("#body").append([$tr1, $tr2, $tr3]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
<table>
You have to clone $td, so that DOM treats it as a new element.
var $tr = $("<tr>"),
$td = $("<td>");
var date = '2018-01-01'
$td.text(date);
$tr.append($td.clone());
$td.text("New Years");
$tr.append($td.clone());
$("#body").append($tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
<table>
You can try next code without jquery:
let tbody = document.querySelector('#body');
let tr = document.createElement('tr');
let td = document.createElement('tr');
td.textContent = '2018-01-01';;
let tdClone = td.cloneNode();
tdClone.textContent = "New Years";
tr.append(td,tdClone);
tbody.append(tr);
I think that is true way, because you can create new td instead of clone created td (maybe for example this td has special classes or atributes), and you code repaint DOM only after insert tr in table.
Hmm... Maybe this could be an alternative to do that:
var texts = ["2018-01-01", "New Years"];
$.each(texts, function(i, val){
$("<tr><td>"+val+"</td></tr>").appendTo("#body")
});
$.each gets each item on the array texts, wrap it on tr and td, then append to the result on #body.
working fiddle
Related
<table id="mytable">
<tr>
<td> 1.<a class="mybk" href="/sample/samples/sample.php?mybookid=2000"> PROFESSIONAL EDUCATIONAL</a></td>
</tr>
<tr>
<td> 2.<a class="mybk" href="/sample/samples/sample.php?mybookid=2001"> New EDUCATIONAL</a></td>
</tr>
........
.
</table>
From the HTML I can able to get the tr, td value as
1.<a class="mybk" href="/sample/samples/sample.php?mybookid=2000"> PROFESSIONAL EDUCATIONAL</a>
..etc
my question is on the each row how can i get the anchor tag href value
My code is :
$('#mytable> tbody > tr').each(function() {
var name = $(this).find("td").eq(0).html();
var href = $(".mybk").attr('href');
}
I got only first href values for all the loop. How can i get each time each row a tag href value ??
Try to change it to working "in context"
$('#mytable> tbody > tr').each(function() {
var tData = $(this).find("td").eq(0);
var name = tData.html();
var href = $(".mybk", tData).attr('href');
var bookId = href.match(/mybookid=(\d+)/)[1];
});
http://jsbin.com/lijeq/1/
Because you're asking for that value:
var href = $(".mybk").attr('href');
IE: the first element with class .mybk encountered
try this:
$(function(){
$('#mytable> tbody > tr').each(function() {
var name = $(this).find("a").text();
var href = $(this).find("a").attr('href');
console.log(name,href);
});
})
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.
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.
Below I have the code that allows me to edit a table row inline. However it edits ALL of the TDs within that row. My problem, along with the code, are stated below. Any help is appreciated.
<tbody>
<tr>
<th scope="row">Test</th>
<td class="amount">$124</td>
<td class="amount" id="" >$154</td>
<td class="diff">- 754</td>
</tr>
</tbody>
The above table is just a sample. What I have been trying to accomplish is, to simply edit the TDs within that particular row, but I need it to disregard the diff TD.
I'm fairly new to jQuery and have got the following code via the help of a jQuery book.
$(document).ready(function() {
TABLE.formwork('#current-expenses');
});
var TABLE = {};
TABLE.formwork = function(table){
var $tables = $(table);
$tables.each(function () {
var _table = $(this);
_table.find('thead tr').append($('<th class="edit"> </th>'));
_table.find('tbody tr').append($('<td class="edit"><input type="button" value="Edit"/></td>'))
});
$tables.find('.edit :button').live('click', function(e) {
TABLE.editable(this);
e.preventDefault();
});
}
TABLE.editable = function(button) {
var $button = $(button);
var $row = $button.parents('tbody tr');
var $cells = $row.children('td').not('.edit');
if($row.data('flag')) { // in edit mode, move back to table
// cell methods
$cells.each(function () {
var _cell = $(this);
_cell.html(_cell.find('input').val());
})
$row.data('flag',false);
$button.val('Edit');
}
else { // in table mode, move to edit mode
// cell methods
$cells.each(function() {
var _cell = $(this);
_cell.data('text', _cell.html()).html('');
if($('td.diff')){
var $input = $('<input type="text" />')
.val(_cell.data('text'))
.width(_cell.width() - 16);
_cell.append($input);
}
})
$row.data('flag', true);
$button.val('Save');
}
}
I have attempted to alter the code so that it would disregard the diff class TD, but have had no luck so far.
Replace
var $cells = $row.children('td').not('.edit');
with
var $cells = $row.children('td').not('.edit').not('.diff');
Add one more line after:
var $cells = $row.children('td').not('.edit').not('.diff');
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>');