How to add 'style' in dynamically created table? - javascript

I have created table through DOM, now want to add style to that table but its not working.
code :
<script>
var nrCols=4;
var maxRows=10;
var nrRows=maxRows+1;
while(nrRows>maxRows)
{
nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
}
var root=document.getElementById('mydiv');
var tab=document.createElement('table');
var style=document.createElement('style');
style.setAttribute('background-color','red');
tab.appendChild(style);
tab.setAttribute('Border','1');
tab.className="mytable";
var tbo=document.createElement('tbody');
var tr1= document.createElement('tr');
var th1= document.createElement('th');
th1.appendChild(document.createTextNode('No.'));
var th2= document.createElement('th');
th2.appendChild(document.createTextNode('Surah.'));
tr1.appendChild(th1);
tr1.appendChild(th2);
tbo.appendChild(tr1);
var row, cell;
for(var i=0;i<nrRows;i++){
row=document.createElement('tr');
for(var j=0;j<nrCols;j++){
cell=document.createElement('td');
cell.appendChild(document.createTextNode('Allah'+' '+j))
row.appendChild(cell);
}
tbo.appendChild(row);
}
tab.appendChild(tbo);
root.appendChild(tab);
</script>
i have used style.setAttribute('background-color','red'); but no difference. how to fix it ?

Replace
var style=document.createElement('style');
style.setAttribute('background-color','red');
tab.appendChild(style);
with :
tab.style.backgroundColor = 'red';
All elements have a style attribute to which you can add the appropriate style values.

try to change the name of var style it might be causing the css style confusion, try this way
var menu = document.createElement("menu");
menu.style.backgroundColor = "#555";

Well, style is a HTML tag, when you create a element with that name it expects CSS info inside it. You maybe want this:
If you want to target the <th> element you should use this instead:
var th1 = document.createElement('th');
th1.style.backgroundColor = 'red';
Demo

it should be something like this
document.body.style.backgroundColor="#333333";
in your case
tab.style.backgroundColor="#333333"
Below code will create style tag
var css = 'table { background: red; }'
var style = document.createElement('style');
style.styleSheet.cssText = css;

Related

Accessing an object's content in Javascript

I'm pretty new to Javascript. I just have a basic question. Can somebody tell me why executing the javascript code in the JSFiddle link below results in this error:" Cannot read property 'innerHTML' of null".
Link:
http://jsfiddle.net/ali89ma/tz5h8umk
var myTable = document.createElement("TABLE");
var row1 = myTable.insertRow(-1);
var cell1 = row1.insertCell(-1);
cell1.innerHTML = "23.00";
cell1.id = "1000price";
var cell1Content = document.getElementById("1000price").innerHTML;
console.log(cell1Content);
But if I write the line below it works fine.
var cell1Content = cell1.innerHTML;
console.log(cell1Content);
Thanks.
as mentioned above The getElementById() method returns the element that has the ID attribute from the DOM with the specified value.
you create a table element dynamiclly but you didnt append it to your page(this will add the table to the DOM elements)
so you need to add this append order to your code like that :
// create a table element dynamiccly but it still not in the DOM elements
var myTable = document.createElement("TABLE");
var row1 = myTable.insertRow(-1);
var cell1 = row1.insertCell(-1);
cell1.innerHTML = "23.00";
cell1.id = "1000price";
//the next line will add your table to the DOM
document.body.appendChild( myTable );
//now you can use the getElementById method to get elements from the DOM
var cell1Content = document.getElementById("1000price").innerHTML;
console.log(cell1Content);
insertCell returns null if the parent table does not exist in the DOM.
Add this line immediately after line 1:
var myTable = document.createElement("TABLE");
document.body.appendChild( myTable ); // <-- this line
var row1 = myTable.insertRow(-1);
After adding the line it works and I get "23.00" output in my console.
You must append element after create
var myTable = document.createElement("TABLE");
document.body.appendChild(myTable);
You are creating the table through javascript. When you are trying to access the table element it will not be present in the DOM. You need to add the table to the DOM then it will work. Add this line able the var cell1Content
document.body.append(myTable);
append table in body before accessing element
var myTable = document.createElement("TABLE");
document.body.appendChild(myTable);
working fiddle
http://jsfiddle.net/tz5h8umk/2/

How to generate a table of colors?

I'm trying to create a table with 32 buttons.
Each button generated must have the name of a color (in turn generated for the button).
If I click on the button, placed in the table, the page background color should be with the text (color) displayed on the pressed button.
I thought about this:
var tableRef = document.getElementById('table').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.id = "row"
Can you do this?
What advice could you give me the components to be used?
I making this in Javascript code.
Advice:
Create the entire thing using Javascript.
function createTable(){
var body=document.getElementsByTagName('body')[0];
var tbl=document.createElement('table');
tbl.setAttribute('id', tableID);
var tbdy=document.createElement('tbody');
for(var i=0;i<4;i++){
var tr=document.createElement('tr');
for(var j=0;j<8;j++){
var td=document.createElement('td');
var bt = document.createElement('button');
// add button attributes
td.appendChild(bt);
tr.appendChild(td)
}
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
}
then you create the onclick method
function changeColor(color){
var body=document.getElementsByTagName('body')[0];
body.style.bgColor = color;
}
Mind you I'm doing this from memory, if the bgcolor doesn't work then try something else

can't add text over image dynamically

I'm designing mobile webpage using HTML5+Javascript. I added a image dynamically thro' javascript. But when i tried to set a text over that image dynamically, it doesn't work.
I want the text to be appear over the image.
My code is;
<script>
for(var i=0;i<5;i++) {
var ele = document.getElementById('container');
var table = document.createElement('table');
table.className = 'c1';
var tr = document.createElement('tr');
var td = document.createElement('td');
/* image added dynamically */
var img = new Image();
img.src = "Images/car.jpeg";
img.className = 'c3';
var txt = document.createTextNode('IE8');
td.appendChild(img);
img.appendChild(txt);
tr.appendChild(td);
table.appendChild(tr);
ele.appendChild(table);
}
<style> .img{height:50px;width:50px;}
.c1 {height:60px; width:100px;}
</style>
<body id='container'></body>
I have tried by adding a div component & then adding text + background-image to it. It's also not working.
Better choice whould be to set the image as CSS image-background property of the text container.
<td style="background-image: url('path_to_image');">
A not so good technique would be putting the text on a container floating, with an absolute position (this whould require JS) and z-index greater than the image element.
Try this as #Edorka suggests
td.backgroundImage="url('Images/car.jpeg')";
don't create img element.

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.

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.

Categories

Resources