I want to create a JavaScript function that parses my HTML page, get the Table by it's ID, and after that, add a class attribute to each <tr> as if the line is the 1st, I'll add :
class="line1" to the <tr>
but if the line is the second, I'll add class="line2" to the <tr>
How to do please
If I understand you corrrectly, you want to alternate the class names to get some kind of zebra style right?
var table = document.getElementById('yourTableId');
var rows = table.rows;
for(var i = 0, l = rows.length;i < l; i++) {
rows[i].className = 'class' + ((i%2) + 1);
}
See the HTML DOM Table Object.
its very easy in jquery ... as below :-
$(document).ready(function() {
//for table row
$("tr:even").addClass("AlternateBG1");
$("tr:odd").addClass("AlternateBG2");
})
BUT IN JQUERY...
var table = document.getElementById("yourTableId");
for(var i in table.rows){
table.rows[i].className = 'line'+(i+1).toString();
}
It is easy without jQuery:
oTBody=document.getElementById("tBodyId");
//for (key in oTbody.childNodes) {
for (var nPos=0, nLength = oTbody.childNodes.length; nPos<nLegth; nPos++)}
oRow = oTbody.childNodes[nPos];
if (oRow && oRow.tagName && oRow.tagName.toLowerCase() == "tr") {
oRow.className = (bNormalRow? sClass1:sClass2);
bNormalRow = !bNormalRow;
}
}
With jQuery is really simple, do something like:
var i = 1;
$("#myTable tr").each(function() {
$(this).addClass("line"+i);
i++;
});
Where #myTable is your table id, and $(this) inside each function will be the current element on the cycle.
Related
hi i got the tr content like this way simil
var td = $("tr td"); // get first child of all the td elements
var htmlContent = []; // initilize an empty array
for (i = 0; i < td.length; i++) {
htmlContent[i] = $(td[i]).text();
trid[i] = $(td[i]).attr("id");
}
i want the tr id so i use this code
trid[i] = $(td[i]).attr("id");
but this is not good
You can use .parent() to get the tr, and then its id.
var htmlContent = []; // initilize an empty array
$('tr td').each(function () {
htmlContent.push($(this).text());
console.log($(this).parent().attr('id'));
});
Here is a simple fiddle: https://jsfiddle.net/hxsbLws2/1/
You should use td only since it is already a DOM object. You don't need to use it as a selector again like this $(td) ..
Then just specify the index td[i]
trid[i] = td[i].attr('id');
I have the following HTML table with 5 rows and 5 columns (table.html). I need to insert letter 'A' on each cell. How do I achieve this using javascript?
Using only JavaScript (no jQuery):
JavaScript
var cells = document.getElementsByTagName("td");
for(var i = 0; i < cells.length; i++){
var cell = cells[i];
cell.innerText = "A " + cell.innerText;
}
JSFiddle
EDIT
If you want to target a specific table, you can do this by setting an id on it and using something like this:
var cells = document.getElementById("a-table").getElementsByTagName("td");
JSFiddle
If you are usin jQuery. It is very simple
$('td').each(function(){
$(this).html('A' + $(this).html());
});
Try this, using the selector that suits you, for example:
[].forEach.call(document.querySelectorAll("#table_id td"), function(el){
el.innerHTML = 'A';
});
I'm trying to get data from app engine datastore using javascript and json. it's also allowed jsonp service, here the javascript code:
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
$('#date').text(date);
$('#nohp').text(user);
$('#content').text(content);
}
});
you can also check it here: http://jsfiddle.net/YYTkK/7/
unfortunately, it just retrieve 1 latest data from the datastore. am I doing something wrong with this code?
thanks in advance.
You're not appending elements, but simply changing the value of the same 3 elements in question three times. So you simply overwrite the value you put into it the time before. The easiest way to solve this is to designate the existing tr as a .template and clone it in your loop, make the necessary changes (filling in the values) and then appending it.
Fixing some other unclear things this gives the following
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(records) {
for (var i = 0; i < records.length; i++) {
//Clone the row/unit which we will be using for each record (the class should refer to the type of item it /actually/ is)
row = $(".row.template").clone();
//The template class is hidden, so remove the class from the row/unit
row.removeClass("template");
var map = records[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
//Make the required changes (find looks for the element inside var row)
row.find('.date').text(date);
row.find('.nohp').text(user);
row.find('.content').text(content);
//Append it to the parent element which contains the rows/units
$("tbody").append(row);
}
});
See functional demo: http://jsfiddle.net/YYTkK/13/
You must append a new row in the table in every loop. Here's the working fiddle.
fiddle
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
var row = '<tr><td>'+date+'</td><td>'+user+'</td><td>'+content+'</td></tr>';
$('#valuetable').append(row);
}
});
what you have to do is create dynamic "tr" s and append to tbody and use thead for header and separate the body using tbody and create tr s on each iteration and after the loop append that tr to tbody. that will do the job, as you do now it will override the values at each iteration.
#chamweer answer is correct you have to create a new tr with td's dynamically
like this:
http://jsfiddle.net/YYTkK/14/
Because you're overriding the same td's over and over again.
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
// create a temporary tr
var tr = $("<tr />");
// append to the tr the td's with their values
tr.append($("<td />").text(date), $("<td />").text(user),
$('<td />').text(content));
// finally append the new tr to the table's tbody
$("#js-tbody").append(tr);
}
});
How can you get the id of a table when you click an input element?
I don't need the rowId etc.
I've tried parentNode.id but I can't seem to get the id.
In the end I'd like to do something like this:
var tabelid = INPUT....parentNode.parentNode.id;
var table = document.getElementById(tabelid);
Example:
How about this:-
Demo
Html
<table id="tblTest">
<tr>
<td>
<input type="text" id="txtTest" onclick="getParent.call(this)" />
</td>
</tr>
</table>
I am using call here so that i get the elements context inside the getParent event callback.
Javascript
function getParent()
{
var parent = this.parentNode;
var tagName = "table";
while (parent) { //Loop through until you find the desired parent tag name
if (parent.tagName && parent .tagName.toLowerCase() == tagName) {
alert(parent .id);
return;
}
else
{
parent = parent .parentNode;
}
}
}
If you are using Jquery:-
in the click event you can just do $(this).closest('table').attr('id')
If you are using jQuery you can use closest to find the closest matching ancestor like so:
var tableID = "";
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').attr('id');
});
]);
Edit:
If you actually want to do something with that table (for instance add a class), you could do the following:
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').addClass('myClass');
});
]);
This simply removes the need to fetch the table ID, store it, and then fetch the table based on it's ID. Since you already found the table in order to get its ID you can just manipulate it right away.
You have to ascend the DOM from TD to TABLE keeping in mind that browsers may inject a TBODY if you haven't specified it. So, your code should look something like this:
var tableCells = document.getElementsByTagName('td'),
cellCount = tableCells.length,
i;
for (i = 0; i < cellCount; i += 1) {
tableCells[i].onclick = function () {
var tableId = getTableId(this);
console.log(tableId);
};
}
function getTableId(node) {
var element = node;
while (element.tagName.toLowerCase() !== 'table') {
element = element.parentNode;
}
return element.id;
}
Check out the demo.
So let's say I have a table, and I want to manipulate a specific <td> in it:
HTML:
<table>
<tr><td>1</td> <td>2</td></tr>
<tr><td>3</td> <td>4</td></tr>
<tr><td id="hi">5</td> <td>6</td></tr>
</table>
Javascript:
document.getElementsByTagName("table")[0].rows[2].cells[0];
This will help me REACH a specific cell in a table.
My question is this:
Say I have a specific <td> inside a table:
var td = document.getElementById("hi")
I want to KNOW its location in the table, so I can be able to reach it using table.rows[x].cells[y]
How can I check this location?
I'd suggest, as you imply you know which specific cell you want to find, though currently untested:
var td = document.getElementById("hi"),
col = td.cellIndex,
row = td.parentNode.rowIndex;
The cellIndex property of a td element gives the index of the cell in the row.
The rowIndex property of a tr element gives the index of the row in the table.
So,
var td = document.getElementById("hi");
var x = td.cellIndex;
var y = td.parentNode.rowIndex;
You will need something like this:
function getRowCellPosition(table, cell) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++) {
if (table.rows[i].cells[j] === cell) {
return {
row: i,
cell: j
};
}
}
}
return null;
}
or more simple:
function getRowCellPosition(cell) {
return {
row: cell.parentNode.rowIndex,
cell: cell.cellIndex
}
}
Simply create a for loop that goes through each row and column and compare the TD in that index against the one you want.
Try this:
for row:
Array.slice(el.parentNode.parentNode.children).indexOf(el.parentNode)
for col:
Array.slice(el.parentNode.children).indexOf(el)
The slice magick is because el.parentNode.children is not an array.
edit: I wasn't aware of td.cellIndex and tr.rowIndex. Definitely use them.