My homework assignment is to generate a checkered html table (aka a chess board) using javascript. I have to use the getElementById and innerHTML properties to do it. I am supposed to generate html strings and add them to the document.
This is what I've written, when i open the page it is empty though, it isn't generating anything at all.
html/script:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="gameTableStyle.css">
<script>
function showTable() {
var tableDiv = document.getElementById("tableDiv");
tableDiv.innerHTML = genTable();
}
function genTable() {
var html = "";
var i = 0;
var j = 0;
var tClass = "white";
html += "<table>";
for (i = 0; i < 8; i++) {
html += "<tr>";
for (j = 0; j < 8; j++) {
if (i % 2 = 0) {
tClass = "black";
}
else {
tClass = "white";
}
html += "<td>" + "</td>;
}
html += "</tr>";
}
html += "</table>"
return html;
}
</script>
</head>
<body onload="showTable()">
<div id="tableDiv">
</div>
</body>
</html>
css:
.black {
color: black;
}
.white {
color: white;
}
This is my first class on html/javascript so I'm sure there are fancier ways to do this but we are specifically supposed to do it by generating the strings and inserting them in the document. I don't know what I'm doing wrong.
Related
I would like to print a new line in JS, but I can't figure out how to do it without document.write. I need to do it without this because I'm using buttons to call functions, and when I use doc.write, it erases the page and displays the results of the function on its own.
<h3>$$$$$</h3>
<span id = "$"></span>
<button onclick="prob2()">Submit</button>
<script type="text/javascript">
function prob2(){
n = parseInt(prompt("Enter number: "));
for(var i=0;i<n;i++){
for(var j=0;j<=i;j++){
document.getElementById("$").innerHTML = "$";
}
console.log("\n");
}
};
Rather than having console.log there, I want to print a line break on the screen so that my output looks like this:
$
$$
$$$
...
EDIT:
Based on Anurag's first suggestion, I built a string and used it with innerHTML to achieve my desired output.
function prob2(){
var str = "";
var num = parseInt(prompt("Enter number: "));
for(var i=0;i<num;i++){
for(var j=0;j<=i;j++){
str += "$";
}
str += "<br>";
}
document.getElementById("$").innerHTML = str;
};
His second suggestion that I accepted as the answer also works!
Here's one way to do it:
function generate() {
document.getElementById("$").innerHTML = ""
var n = parseInt(prompt("Enter number: ")), str = "", currStr = "";
for (var i = 0; i < n; i++) {
str = "", currStr = document.getElementById("$").innerHTML
for (var j = 0; j <= i; j++) {
str+= "$"
document.getElementById("$").innerHTML = currStr + str + "<br/>";
}
}
};
<h3>Incremental $</h3>
<span id="$"></span>
<button onclick="generate()">Generate</button>
I interpreted the question differently. I thought the purpose was to replace the use of the document.write() statement.
<!DOCTYPE html><html lang="en"><head><title> Test Page </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- For: https://stackoverflow.com/questions/62742502/how-can-i-print-a-new-line-in-js-without-using-document-write -->
<style>
p { background-color: lime; }
pre { border: 1px solid red;}
div { border: 3px dotted blue }
</style>
</head><body>
<script>
newLine = (tag,msg) => {
var elem = document.createElement(tag);
elem.appendChild(document.createTextNode(msg));
document.body.appendChild(elem);
// Note: .body. could be a different element or another parameter added to function
}
newLine('p','New line has been created.');
newLine('pre','And then another.');
newLine('div','And then one final new line to display.');
</script>
</body></html>
Remove the CSS styling as it was only added for emphasis.
I'm trying to use document.getElementByClassId().style.color to change the color of an element in my HTML document. I can see that it does add an inline style tag to the element but they are seemingly ignored by the browser.
I tried using the !important tag but that changed nothing. Here is my HTML document. I changed my CSS for the elements I want to modify into inline tags but they are ignored as well. Everything else works so far.
Here is my code (I'm a beginner please go easy on me :/).
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel">';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.color = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
You have to style the backgroundColor instead of color, because the cells don't contain any text, to which the color would be applied to
//Only gets used to make the rows array.
var cells = [];
//Array that contains the entirety of the table element.
var rows = [];
//Random number to be used to color a random cell.
var rand = 0;
//Unique ID number that gets applied to each cell on the gameboard.
var id = 0;
//Calls cellMake.
var makeBoard = function(size) {
cellMake(size);
}
//Adds opening and closing tags at the beginning and end of each string then writes them to the rows array.
var rowMake = function(num) {
for(c = 0; num > c; c++) {
rows[c] = '<tr>' + cells[c] + '</tr>';
}
writeBoard();
}
//Writes cell elements to the cells array based on how many columns the makeBoard function was called for.
var cellMake = function(num) {
for(a = 0; num > a; a++) {
cells[a] = '';
for(b = 0; num > b; b++) {
cells[a] += '<td id="' + id + '" class="pixel"></td>';
id++;
}
}
rowMake(num);
}
//Chooses random pixel from the board and sets its color.
var choosePixel = function() {
rand = Math.round(Math.random() * rows.length * rows.length);
console.log(rand);
document.getElementById(rand).style.backgroundColor = 'red';
}
//Writes each element of the rows array onto the HTML document.
var writeBoard = function() {
for(d = 0; rows.length > d; d++) {
document.getElementById('gameboard').innerHTML += rows[d];
}
choosePixel();
}
window.onload = function() {
makeBoard(50);
}
<!DOCTYPE html>
<html>
<head>
<title>Can I write JS?</title>
<script src="script.js"></script>
<style>
body {
text-align: center;
background-color: black;
}
#gameboard {
display: inline-block;
margin: 0 auto;
padding-top: 5%;
}
.pixel {
height: 5px;
width: 5px;
}
</style>
</head>
<body>
<table id="gameboard"></table>
</body>
</html>
I'm trying to create a chess game in javascript. I created a chessboard and the next step is to add an id's and classes to created td's.
Here is the code:
<html>
<head>
<title> Play Chess! </title>
<meta charset="utf-8">
<link rel='stylesheet' href='css/styles.scss' type='text/css'/>
</head>
<body>
<script>
var table ='';
var rows =8;
var cols=8;
for (var r = 0; r<rows;r++){
table +='<tr>';
for(var c=0;c<cols;c++){
table+='<td>' +''+'</td>';
}
table+='</tr>';
}
document.write("<table border=1>"+table+'</table>');
</script>
</body>
</html>
I know I can simply do this with html, but it's too much code and I belive there is other way to do this.
Here is a solution with plain JavaScript (no jQuery). Put the script just before the closing </body> tag. This does not use document.write which really is to be avoided. Instead the HTML has an empty table with an id attribute, which then is populated through script.
var rows =8;
var cols=8;
var table = document.getElementById('board');
for (var r = 0; r<rows; r++){
var row = table.insertRow(-1);
for (var c = 0; c<cols; c++){
var cell = row.insertCell(-1);
cell.setAttribute('id', 'abcdefgh'.charAt(c) + (rows-r));
cell.setAttribute('class', 'cell ' + ((c+r) % 2 ? 'odd' : 'even'));
}
}
table {
border-spacing: 0;
border-collapse: collapse;
}
.cell { width: 20px; height: 20px; }
.odd { background-color: brown }
.even { background-color: pink }
<table id="board"></table>
As a bonus it has the chessboard altering colors, and the id values are running from a1 (bottom-left) to h8 (top-right)
If you can solve this issue by coding the layout directly inside your HTML file, you should definitely do that instead of building it dynamically in JavaScript. This is hugely less error-prone.
That being said, solving this using jQuery is not too hard:
var sideLength = 8;
var table = $('<table>');
$('#root').append(table);
for (var i = 0; i < sideLength; i++) {
var row = $('<tr>');
table.append(row);
for (var j = 0; j < sideLength; j++) {
row.append($('<td>'));
}
}
td {
border: 1px black solid;
width: 10px;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='root'></div>
I am trying to add css class using javascript but its not working
var x = document.getElementsByClassName('oldclassname');
var i;
for (i = 0; i < x.length; i++) {
x[i].className += 'newclassname';
}
but when I tried changing background it works
var x = document.getElementsByClassName("oldclassname");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
Am I doing anything wrong while adding css file
className is a space separated list of class names. The problem with your code is that it doesn't separate the class names with spaces. Try this:
var x = document.getElementsByClassName('oldclassname');
var i;
for (i = 0; i < x.length; i++)
{
x[i].className += ' newclassname'; // WITH space added
}
Without the space, it has only one class name
<div class="oldclassnamenewclassname"></div>
//if use space
<div class="oldclassname newclassname"></div>//get two class name
Better use classList:
var x = document.getElementsByClassName('oldclassname');
for (var i = 0; i < x.length; i++) {
x[i].classList.add('newclassname');
}
.newclassname { color: blue; }
<div class="oldclassname">Hello, world!</div>
Hi there is a much simpler way to do this using javascript
TO add a class: -
document.getElementsByClassName('otherClassName')[0].classList.add('newClassName');
To remove a class:-
document.getElementsByClassName('otherClassName')[0].classList.remove('newClassName');
Hope this helps :)
It works . Check your target class name formation.
Sample Code.
<html>
<head>
<style>
.classFrom{
font-family: sans-serif;
color: red;
}
.classTo{
font-family:cursive;
color: blue;
}
</style>
<script type="text/javascript">
function clickme(){
var elmList = document.getElementsByClassName('classFrom');
for (i = 0; i < elmList.length; i++)
{
elmList[i].className += " classTo";
}
}
</script>
</head>
<body>
<div class="classFrom">SampleText</div>
<button onClick="clickme()">ChangeCSS</button>
</body>
</html>
I made a function create_table(...) that is supposed to add the HTML for a table to the end of the inner HTML of a given element. What should be happening the following code is that when I click the Show Tree button, a table should be created inside the third div. For some reason I'm getting the error Property 'getElementById' of object #<HTMLDocument> is not a function. Any help greatly appreciated.
<html>
<head>
<style type="text/css">
div
{
border: 1px dashed;
}
table
{
border: 1px dashed red;
}
#instructdiv
{
}
#inputdiv
{
}
#outputdiv
{
}
</style>
<script type="text/javascript">
function create_table(rows, columns, elementId)
{
/* Adds at the end of the HTML for a container with
elementId the HTML for a table with a specified
number of rows and columns.
*/
var newHTML = document.getElementById(elementId).innerHTML;
newHTML += "<table>";
for (var i = 0; i < rows; ++i)
{
newHTML += "<tr>";
for (var j = 0; j < columns; ++j)
newHTML += "<td>j</td>";
newHTML += "</tr>";
}
newHTML += "</table>";
document.getElementById = newHTML;
}
function make_tree()
{
/* To do: Determine number of rows and columns by user input.
For testing now, just make the table an arbitrary size.
*/
create_table(4,50, "outputdiv");
}
</script>
</head>
<body>
<div id="instructdiv">
<p>In the text field below, enter integers in the range 0 through 127 separated by spaces,
then push Show Tree.</p>
</div>
<div id="inputdiv">
<textarea id="inputText" scrolling="yes"></textarea>
<p></p>
<button onclick="make_tree()">Show Tree</button>
</div>
<div id="outputdiv">
<!-- binary tree table is housed here -->
</div>
</body>
</html>
Change your code to this. You shouldn´t assign document.getElementById ( which is a function ) to an string, because de the function being unusable.
function create_table(rows, columns, elementId)
{
/* Adds at the end of the HTML for a container with
elementId the HTML for a table with a specified
number of rows and columns.
*/
var element = document.getElementById(elementId);
var newHTML = element.innerHTML;
newHTML += "<table>";
for (var i = 0; i < rows; ++i)
{
newHTML += "<tr>";
for (var j = 0; j < columns; ++j)
newHTML += "<td>j</td>";
newHTML += "</tr>";
}
newHTML += "</table>";
element.innerHTML = newHTML;
}
function make_tree()
{
/* To do: Determine number of rows and columns by user input.
For testing now, just make the table an arbitrary size.
*/
create_table(4,50, "outputdiv");
}