Javascript, DOM crazyness... - javascript

First of all, please excuse me as I am a bit new to this so my code does not look pretty... but everything below works, ## this is not a thread asking for help with non working code ##.
Now that thats out of the way... here's the thing: I have made an addon for FF but the addon editor told me it would be rejected as I was using innerHTML... so to change that using appendChild etc, and thats what I did below.
The thing is, it looks ugly and feels really complicated so I was wondering if I used the right approach or is there an easier way of doing this?
var the_table_color,alt_link,link_for_deletion,comment =null;
var xmlDoc=null;
var parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
var nodes = xmlDoc.getElementsByTagName("unblocker_details");
var t = document.createElement("table"),
td = document.createElement("td"),
tr = document.createElement("tr");
var a = document.createElement("a"),
strong = document.createElement("strong");
t.style.width = "80%"; // Table attributes
t.style.border="0";
t.cellspacing="2";
t.cellpadding="2";
for(var i=0; i< nodes.length; i++) {
the_table_color = nodes[i].getAttribute("table_color");
var the_type = nodes[i].getAttribute("type");
alt_link = nodes[i].getAttribute("alt_link");
link_for_deletion = nodes[i].getAttribute("link_for_deletion");
comment = nodes[i].getAttribute("comment");
// TR1, TD1
td=""; td = document.createElement("td");
tr=""; tr = document.createElement("tr");
tr.bgColor=the_table_color;
t.appendChild(tr);
td.width="16%";
td.vAlign="top";
tr.appendChild(td);
strong="";
strong = document.createElement("strong");
strong.appendChild(document.createTextNode(the_type));
td.appendChild(strong);
td.width="16%";
td.vAlign="top";
tr.appendChild(td);
//TD2
td=""; td = document.createElement("td");
td.width="70%";
td.vAlign="top";
a="";a = document.createElement("a");
a.href= alt_link;
a.appendChild(document.createTextNode(alt_link));
a.target= "_blank";
td.appendChild(a);
tr.appendChild(td);
//TD3
td=""; td = document.createElement("td");
td.noWrap="NOWRAP";
td.align="center";
td.vAlign="middle";
td.width="14%";
a="";a = document.createElement("a");
a.href= "javascript:dead_link('"+link_for_deletion+"')";
a.appendChild(document.createTextNode("Dead link?"));
td.appendChild(a);
tr.appendChild(td);
t.appendChild(tr);
// TR2, TD1 (or TD4 in total)
tr=""; tr = document.createElement("tr");
tr.bgColor=the_table_color;
td=""; td = document.createElement("td");
td.vAlign="top";
td.appendChild(document.createTextNode("Comment:"));
tr.appendChild(td);
td=""; td = document.createElement("td");
td.colSpan="2";
td.appendChild(document.createTextNode(comment));
tr.appendChild(td);
t.appendChild(tr);
}// End of for() loop
//alert(t.innerHTML);
document.getElementById("wait").textContent="";
document.getElementById("wait").appendChild (t);

If you don't want to pull in a giant library to do simple stuff you can simply alias the functions:
// aliasing
var el = document.createElement;
// not really aliasing, but I didn't want to modify the prototypes of html elements
function attr(el, attr, value) {
el.setAttribute(attr, value);
}
Changes your code to look something like this:
var td = el('td');
attr(td, 'width', '100%');
Though with jQuery this would look like this:
var td = $('<td>');
td.attr('width', '100%');
Though I'm usually stingy and write a wrapper around jQuery (especially for divs) that tends to look like this:
function div(className) {
if(className) {
return $('<div>', {'class': className});
}
return $('<div>');
}

The ugly thing I see is the setting of attributes without using setAttribute()
If you like to have a kind of snippets, this can be done without using innerHTML, you already use the needed method inside your code.
An simple example that creates a table in 1 step:
var table = parser.parseFromString('<table>'+
'<tr><td>table created without innerHTML</td></tr>'+
'</table>',
'text/xml').documentElement;

JQuery is a lightweight library that does all of what you wish to do in there, and it guarantees cross browser compatibility.

Related

How to id dom table so I can position it on page?

I am new to creating tables with js and started with using document.write. That was writing over my html so now I am using dom elements. How can I id the group of tables so I can position it in my css? I am a little confused how because my code creates multiple tables with the loop. I would just like to position them all as one. The picture shows what they look like but they just default to the bottom/left of my page. Also would appreciate any other code suggestions since I am new at this! Thanks!
<script type="text/javascript">
BuildTable();
function BuildTable() {
var myUrl = window.location.href;
PageMethods.DoStuff(myUrl, onSucess, onError);
function onSucess(result) {
for (var i = 0; i < result.length; i++) {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var row = document.createElement("tr");
var cell = document.createElement("td");
var cellText = document.createTextNode('Community: ' + result[i].apartName);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
row = document.createElement("tr");
cell = document.createElement("td");
cellText = document.createTextNode('Address: ' + result[i].address + ', ' + result[i].city);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "1");
var space = document.createElement("br");
body.appendChild(space);
}
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
To set the id:
tbl.setAttribute('id', thisTablesId );
But probably what you want is to set the class attribute instead. Those don't need to be unique. You can change the css styles (for positioning) of all tables with the same class at once. Or if you need to programmatically determine the styling, you can use that attribute to determine whether or not this is one of the elements you wanted.
tbl.setAttribute('class', 'built-table' );
In your css stylesheet you can define what the built-table class will include using the .built-table selector.

Go step by step through the html table

I need to insert some value into html table dynamically. For example, I have some inputs and then I have a table (about 5 rows), so I have one button which enables a timer. When the timer is stopped I need to insert data into table.
Here is the code, how do I add data to one row?
document.getElementById('d1').innerHTML = document.getElementById('ctrl_ball_size_val').value;
document.getElementById('l1').innerHTML = document.getElementById('ctrl_cilindr_height_val').value;
document.getElementById('t1').innerHTML = document.getElementById('stopwatch').value;
How can I add data (data can be different) to the table row by row?
It is highly recommended to avoid using innerHTML for this task.
I suggest to use the DOM to achieve that.
Here is a quick example on how you can create HTML table dynamically using JavaScript:
var tbl = document.createElement("table");
for(var i=0;i<=10;i++){
var tr = document.createElement("tr");
for(var j=0;j<=10;j++){
var td = document.createElement("td");
td.innerHTML = i*j;
tr.appendChild(td);
}
tbl.appendChild(tr);
}
document.body.appendChild(tbl);
Check out my Live example
If you are using JQuery Simply use:
$('#tableID > tbody > tr').each(function() { //Acess $(this) });
And you Never Need it then?
as per jQuery each loop in table row, just a bit of code:
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}

Find last td without using Jquery

I need to find the Last td of every row in a HTML table, and remove a css from that td. Can I do it without using Jquery.
How?
You can use css3 last-child property for this. Write like this:
tr td:last-child{
color:red;
}
But it's not work in IE8 & below.
Use CSS
td:last-child: {
//your style here
}
Docs on CSS3 selectors here
or using traverse the DOM using JavaScript :
var mytable = document.getElementById('tableid');
var myrows = mytable.getElementsByTagName("tr");
var lastrow = myrows[myrows.length -1];
var mycells = lastrow.getElementsByTagName("td");
var lastcell = mycells[mycells.length -1];
// set CSS property here
lastcell.style.color = "red";
lastcell is your last td
Working example using JavaScript
Have you tried using CSS3 selectors? E.g
tr td:last-child
{
YOUR CODE HERE
}
You could also look at using classes to show which td's are the last. But of course this isnt dynamic.
I believe there is also a normal javascript answer but im not very good at that :P
http://www.w3.org/TR/selectors/
http://www.quirksmode.org/css/firstchild.html
Assuming that you are not looking for css type solution
rows=document.getElementsByTagName('tr')
for (var i=0; i<rows.length; i++){
columns=rows[i].getElementsByTagName('td');
mytd = columns[columns.length-1];
classname = mytd.className;
arr = classname.split(' ');
mytd.className = arr.filter(function(e){return e!=CLASSTOREMOVE}).join(' ');
}
For a pure JavaScript solution:
function removeCssClass(tableId, cssClass) {
var trs = null;
var tr = null;
var tds = null;
var td = null;
var classes = [];
var i = 0;
trs = document.getElementById(tableId).getElementsByTagName('tr');
tds = trs[trs.length - 1].getElementsByTagName('td');
td = tds[tds.length - 1];
classes = td.className.split(' ');
for (i = 0; i < classes.length; i += 1) {
if (classes[i] === cssClass) {
classes.pop(i);
}
}
td.className = classes.join(' ');
return false;
}​
Working fiddle.
What are you trying to do with the last TD? If you are wanting to have a border in-between each td why don't you use border-left and then you can use first-child to remove it. There might be a better approach that is more compatible with browsers.

InvalidArgument with HTML Table's insertBefore method

I think I know this is an IE bug ...
I need to add new row to an HTML table at the exact position.
(don't want insertRow(index) cuz this looks like gonna be better for some other reasons)
function AddNewItem(td) { ///td comes from button at the HTML code, <input ... onclick="AddNewItem(this.parentNode)"
var grid = GetGrid();
var itemIndex = $(td.parentNode).attr('index');
///alert(itemIndex + "'e eklenecek");
var newRow = document.createElement('tr');
var td1 = document.createElement('td');$(td1).addClass('td');
var td2 = document.createElement('td');$(td2).addClass('td text r');
var td3 = document.createElement('td');$(td3).addClass('td text r');
var td4 = document.createElement('td');$(td4).addClass('td text r');
$(newRow).append(td1);$(newRow).append(td2);$(newRow).append(td3);$(newRow).append(td4);
grid.insertBefore(newRow, td.parentNode); ///THIS GIVES AN INVALIDARGUMENT error .. Any solutions will be appreciated :)
}
function GetGrid() {
var grid = document.getElementById("MasterTableView");
return grid;
}
My guess is that td.parentNode is not a child element of grid. Take a look at the W3C specification for insertBefore to make sure that you are calling the method with valid parameters.
I would guess that you're passing in an invalid argument to AddNewItem, that (in IE, at least) it's not a td element like you think.

Create link in an html table with javascript

I am using the following code to add columns dynamically to a html table:
var tblHeadObj = window.opener.document.getElementById("maintable").tHead;
var j=0;
while(j < fname.length)
{
if(tblHeadObj != null)
{
for(var h = 0; h < tblHeadObj.rows.length; h++)
{
var newTH = window.opener.document.createElement('th');
tblHeadObj.rows[h].appendChild(newTH);
//newTH.innerHTML='[th]row:'+h+'cell:'+(tblHeadObj.rows[h].cells.length-1)
}
}
var tblBodyObj = window.opener.document.getElementById("maintable").tBodies[0];
//for(var i = 0; i < tblBodyObj.rows.length; i++) {
var newCell=tblBodyObj.rows[0].insertCell(-1);
var newCell=tblBodyObj.rows[0].insertCell(-1);
// newCell.innerHTML = (tblBodyObj.rows[0].cells.length - 1)
newCell.innerHTML= fname[j];
j++;
}
Now i want to make columns as link.How can i do that?
Thanks
As others have noted, it is quite unclear what you mean by "make columns as link". However, we as a community have become accustomed to making guesses about the real problem and providing a solution based on that assumption. As we gain experience tackling more and more unclear questions, our ESP skill become more honed.
It appears that you are creating an HTML table via DOM methods. I will assume that you want to create a link within the created tablecell and here is my suggestion:
Use the same createElement method to create any elements you need. For instance, a link (anchor) can be created with the following code:
var link = document.createElement("a");
link.setAttribute("href", "http://www.microsoft.com")
link.className = "someCSSclass";
// For IE only, you can simply set the innerText of the node.
// The below code, however, should work on all browsers.
var linkText = document.createTextNode("Click me");
link.appendChild(linkText);
// Add the link to the previously created TableCell.
newCell.appendChild(link);
Alternatively, you can also set the innerHTML of the TableCell as #Anonymous has suggested.
If you're trying to put the cell contents into an anchor, then one way is to change
newCell.innerHTML= fname[j];
to
newCell.innerHTML= ''+fname[j]+'';
where whatever is a variable holding an appropriate string.
Beware that the contents of fname[j] are all inline (eg, not tables or blocks like div, headings, forms -- but form inputs are okay) or the anchor will be closed by most browsers prematurely. If need be, you could put the anchor only around parts of the cell's contents, but the easiest way to do that would depend on what the contents are.
This are all good but I needed an image in the link so here is that code:
cell[k] = document.createElement('td');
var link = document.createElement('a');
link.setAttribute('href', "http://www.ilovethismusic.com");
link.setAttribute('target', "_blank");
var newimg = document.createElement('img');
newimg.src = "http://www.ilovethismusic.com/Views/Images/bg_header.jpg";
newimg.alt = "imageMissing";
newimg.width = "95";
newimg.height = "45";
newimg.border = "0";
link.appendChild(newimg);
cell[k].appendChild(link);

Categories

Resources