this should be an easy one: I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var table = document.createElement("table");
table.setAttribute("id","table");
var headRow = document.createElement("tr");
var dataRow = document.createElement("tr");
var head = document.createElement("th");
var data = document.createElement("td");
head.innerHTML="head";
data.innerHTML="data";
headRow.appendChild(head);
dataRow.appendChild(data);
table.appendChild(headRow);
table.appendChild(dataRow);
console.log(document.styleSheets);
table.className = "table";
document.getElementById("test").appendChild(table);
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
The problem is: The style specified in the bootstrap.min for the class "table" is never applied upon loading the side. Do I have to do something additionally? I test it in the most recent version of Safari.
Any Help?
Cheers Twerp
It is not dynamically created issue. It is because you haven't set the class to table. As Bootstrap Docs says:
You have to use <thead> and <tbody> for the class to work.
To add in your answer:
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
Add this for a quick fix:
$("tr:first-child").wrap("<thead/>");
Your final code should look like:
var table = document.createElement("table");
table.setAttribute("id","table");
var headRow = document.createElement("tr");
var dataRow = document.createElement("tr");
var head = document.createElement("th");
var data = document.createElement("td");
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
head.innerHTML="head";
data.innerHTML="data";
headRow.appendChild(head);
dataRow.appendChild(data);
table.appendChild(thead);
table.appendChild(tbody);
console.log(document.styleSheets);
table.className = "table";
document.getElementById("test").appendChild(table);
The slight difference in styling is because Bootstrap relies on the <tbody> and <thead> elements to apply styling. If you're dynamically creating elements, you need to create these too:
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
Then, instead of appending headRow and dataRow directly, append the newly created elements:
table.appendChild(thead);
table.appendChild(tbody);
Example Fiddle
$(function () {
var table = $('<table></table>').attr('id', 'table').addClass('table')
var head = $('<th></th>').html('head')
var data = $('<th></th>').html('data')
var headRow = $('<tr></tr>').append(head)
var dataRow = $('<tr></tr>').append(data)
table.append(headRow)
table.append(dataRow)
console.log(document.styleSheets);
$('#test').append(table);
})
Best way to add style sheet to dynamically added content is to use classList
Please refer below link:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
OR
You can use element.style.cssProperty
Related
This question already has answers here:
How to run a function when the page is loaded?
(11 answers)
Closed 2 months ago.
Why is getActivityTables() not defined? The script is properly linked, and the function name is the same in the html as well as js file.
What am I doing wrong?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Fitnessapp</title>
<script src="scripts.js"></script>
</head>
<body onload="getActivityTables()">
<div id="" class="container">
<div class="activityDiv">
<h1>Running Activities</h1>
<table id="runningActivity-table" class="table">
</table>
</div>
</div>
</body>
</html>
JS (scripts.js):
function getActivityTables() {
console.log("test");
// Get runningActivity-table
let xhttp = new XMLHttpRequest();
xhttp.onload = function () {
let response;
let responseString = xhttp.responseText;
response = JSON.parse(responseString);
console.log(response);
let table = document.getElementById("runningActivity-table");
let row, cell;
let header = table.createTHead();
row = header.insertRow(0);
cell = row.insertCell();
cell.innerHTML = "ID";
cell = row.insertCell();
cell.innerHTML = "Date";
cell = row.insertCell();
cell.innerHTML = "Duration";
cell = row.insertCell();
cell.innerHTML = "Distance";
cell = row.insertCell();
cell.innerHTML = "Description";
for (let i = 0; i < response.length; i++) {
row = table.insertRow();
cell = row.insertCell();
cell.textContent = response[i].id;
cell = row.insertCell();
cell.textContent = response[i].dateOfCreation;
cell = row.insertCell();
cell.textContent = response[i].durationInMinutes;
cell = row.insertCell();
cell.textContent = response[i].distanceInKm;
cell = row.insertCell();
cell.textContent = response[i].description;
}
}
xhttp.open("GET", "/getRunningActivities");
xhttp.send();
}
I cannot find the problem. I have the exact same code for another page and thats working properly.
I copied your entire code exactly in my vs code, and launched it, and everything is working.
The getActivityTables function worked fine.
But you can try to use the addEventListener() inside the javascript itself, it's better than the regular html events attributes.
But your code doesn't have any problems, I tried it myself.
You can capture the console and the network tab in your browser then we can figure out what's happened.
try to remove <script src="scripts.js"></script> from the head tag And put it at the end of the Body tag
like this :
<body onload="getActivityTables()">
<div id="" class="container">
<div class="activityDiv">
<h1>Running Activities</h1>
<table id="runningActivity-table" class="table">
</table>
</div>
</div>
<script src="scripts.js"></script>
</body>
if problem still
in scripts.js file add :
window.addEventListener('load',getActivityTables())
I need to create a table populated with buttons. Each button must have a unique id in order to edit values in it's row. I set an alert displaying button's id on click, but all created buttons seem to have the same ID. What's wrong with my code?
plz help, im really newbie in js. Any help will be highly appreciated.
this is my code:
<!doctype html>
<html>
<head>
<title>js table</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<table id="TableA" dir="ltr" width="500" border="1">
<tr>
<td>Old top row</td>
</tr>
</table>
</body>
<script type="text/javascript" >
for (var i = 0; i<6; i++) {
// Get a reference to the table
var tableRef = document.getElementById("TableA");
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
// Insert a cell in the row at index 0
var boton = newRow.insertCell(0);
// Append a text node to the cell
var newButton = document.createElement("BUTTON");
newButton.id = i;
newButton.innerHTML = "Unique id button";
boton.appendChild(newButton);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createElement("P");
newText.innerHTML = "item" +" "+ i;
newCell.appendChild(newText);
newButton.onclick = function(){
alert("Button Id: " + newButton.id);
}
}
</script>
Change your client handler to refer to the actual button that was clicked. Change from this:
newButton.onclick = function(){
alert("Button Id: " + newButton.id);
}
to this:
newButton.addEventListener("click", function(e) {
alert("Button Id: " + this.id);
});
The variable newButton is used over and over again in your for loop so by the time any of your onclick handlers actually run, all the buttons have been created and newButton will contain the last value it ever had.
Instead, you can use this to refer to the element that was clicked on so this.id will the id value of the button that was clicked.
Note: I also switch to using .addEventListener() which also passes an event data structure to the event handler (shown as the e argument in my code). This is a generally better way to register event listeners as it allows multiple listeners and gives you automatic access to other info about the event that occurred.
The code below will dynamically create 5 table rows. I dont understand why td.length returns 0 even though I already created it. Can someone explains to me why?
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
var table = $("#mytable");
for(var c=1; c<6; c++){
var id = "#row" + c;
var tr = $("<tr><td id="+id+">Row "+c+"</td></tr>");
table.append(tr);
}
var td = $("#row1");
alert(td.length);
});
</script>
</head>
<body>
<table id="mytable">
</table>
</body>
</html>
The id value itself should not contain the #.
Change this:
var id = "#row" + c;
to this:
var id = "row" + c;
The selector that you use with jQuery contains the #, but not the id value itself.
I have to insert a td inside a tr which has a ID using javascript.Can someone please help me or guide me in the right direction.Sorry it might be simple but I m very new to javascript.
<html>
<head>
<script type="text/javascript">
function insertText ()
{
//function to insert any text on the tr with id "tr1"
}
</script>
</head>
<body onload="javascript:insertText()">
<table>
<tr id="tr1">
</tr>`
</table>
</body>
</html>
function insertText ()
{
var td = document.getElementById('tr1').insertCell(0);
td.innerHTML = "Some Text";
}
The main advantage of insertCell (and insertRow) is that they allow you to specify an index where the new cell (or row) is to be inserted.
Try this:
function insertText ()
{
var el = document.createElement('td');
el.innerHTML = 'Hello World';
document.getElementById("tr1").appendChild(el);
}
Why the following code doesn't work?
<html>
<head>
<script type="text/javascript">
function addTable() {
var table = document.createElement('table');
table.innerHTML = "<tr><td>123</td><td>456</td></tr>";
document.getElementById("addtable").appendChild(table);
}
</script>
</head>
<body>
<input type="submit" value="New Table" onClick="addTable()"/>
<div id="addtable"></div>
</body>
</html>
To the best of my knowledge, setting the innerHTML property of a table element or table section element (like tbody or thead) does not work on Internet Explorer (EDIT: I just checked - with ietester and plain IE8. Result is "unknown runtime error" for IE6 and IE8, and it crashes IE7 but that might be an IEtester specific problem).
The DOM standard way of adding rows to a table is using the insertRow() method on a table or table section element (look for HTMLTableElement and HTMLTableSectionElement in that DOM spec) :
<script type="text/javascript">
function addTable() {
var c, r, t;
t = document.createElement('table');
r = t.insertRow(0);
c = r.insertCell(0);
c.innerHTML = 123;
c = r.insertCell(1);
c.innerHTML = 456;
document.getElementById("addtable").appendChild(t);
}
</script>
In the script, there is no explicit table section being created. AFAIK, a TBODY is automatically created, and rows are inserted in there.
EDIT: regarding IE, I should point out that you can add a table with content and all by setting the innerHTML property, but the html you inject in there must be a complete table. So this does work, even on IE:
<script type="text/javascript">
function addTable() {
var html = "<table><tr><td>123</td><td>456</td></tr></table>";
document.getElementById("addtable").innerHTML = html;
}
</script>
//_table my current table
var table = document.createElement('table'); //new table
table.innerHTML = _table.innerHTML; //clone table innerHTML