The use of JavaScript within the code results in the <header> and <nav> elements failing to display on the browser

Currently, I am tackling a webpage project that involves using scripts in both the head and section elements to generate a table where clicking on the cells changes their color randomly. However, a glitch seems to be hindering the display of the header and navigation elements upon page load, even though the table and scripts are functioning correctly.

My approach includes utilizing a nested loop in the body section, but I have scoured this platform for potential solutions without success. I also experimented with rearranging the table elements concatenated to a string variable, but that did not resolve the issue either. As a last resort, I adjusted the float property for the nav and section elements in my external stylesheet (not provided).

Within the head element (including embedded CSS):

<script>
function myFunction(e) {
      var colorstring = ["green", "lightgreen", "blue", "pink", "yellow", "purple", "brown", "red", "orange", "black"];
      var index = Math.floor((Math.random() * 9) + 1);
      e.innerHTML = colorstring[index];
      e.style.backgroundColor = colorstring[index];
    }
</script>

<style>
    h3 {
        text-align: center;
    }

   table {
       margin: 0 auto;
       width: 50%;
      }

   table,
   td {
       border: 1px solid;
       border-collapse: collapse;
   }

   table td {
       text-align: center;
       width: 25%;
       height: 1.5em;
   }
</style>

Include the header, nav, and section elements (all within the body element):

<header>
    <img src="Fonts/Proj6_heading.png" />
</header>

<nav class="verticalNAV">
    <ul>
        <li><a href="Home_Page.html">Our Services</a></li>
        <li><a href="Growing_Pumpkins.html">Growing Pumpkins</a></li>
        <li><a href="Currency_Converter.html">Currency Converter</a></li>
        <li><a href="Add_Table_Block.html">Add Table Block</a></li>
    </ul>
</nav>

<section>
    <h2>&#60;Add Table Block&#62;</h2>

    <script>
        var string = "";
        string = string + "<h3>Add &#60;Table&#62; Block</h3>";
        string = string + "<table>";
        for (index = 0; index <= 4; index++) {
            string = string + "<tr>";
            for (index2 = 0; index2 <= 3; index2++) {
                string = string + "<td onclick='myFunction(this)' width='20%'>Click Me!</td>"
            }
            string = string + "</tr>";
        }
        string = string + "</table>";
        document.body.innerHTML = string;
    </script>
</section>

function myFunction(e) {
  var colorstring = ["green", "lightgreen", "blue", "pink", "yellow", "purple", "brown", "red", "orange", "black"];
  var index = Math.floor((Math.random() * 9) + 1);
  e.innerHTML = colorstring[index];
  e.style.backgroundColor = colorstring[index];
}

var string = "";
string = string + "<h3>Add &#60;Table&#62; Block</h3>";
string = string + "<table>";
for (index = 0; index <= 4; index++) {
  string = string + "<tr>";
  for (index2 = 0; index2 <= 3; index2++) {
    string = string + "<td onclick='myFunction(this)' width='20%'>Click Me!</td>"
  }
  string = string + "</tr>";
}
string = string + "</table>";
document.body.innerHTML = string;
h3 {
  text-align: center;
}

table {
  margin: 0 auto;
  width: 50%;
}

table,
td {
  border: 1px solid;
  border-collapse: collapse;
}

table td {
  text-align: center;
  width: 25%;
  height: 1.5em;
}
<header>
  <img src="Fonts/Proj6_heading.png" />
</header>

<nav class="verticalNAV">
  <ul>
    <li><a href="Home_Page.html">Our Services</a></li>
    <li><a href="Growing_Pumpkins.html">Growing Pumpkins</a></li>
    <li><a href="Currency_Converter.html">Currency Converter</a></li>
    <li><a href="Add_Table_Block.html">Add Table Block</a></li>
  </ul>
</nav>

<section>
  <h2>&#60;Add Table Block&#62;</h2>
</section>

Answer №1

When utilizing the code

document.body.innerHTML = string;
, it essentially replaces the existing content of document.body with the new string content. To add to the existing content instead, you should use += like this:
document.body.innerHTML += string;
. Alternatively, you can use
document.body.appendChild(string);

function addColor(e) {
  var colors = ["green", "lightgreen", "blue", "pink", "yellow", "purple", "brown", "red", "orange", "black"];
  var index = Math.floor(Math.random() * 9) + 1;
  e.innerHTML = colors[index];
  e.style.backgroundColor = colors[index];
}

var string = "";
string += "<h3>Add &#60;Table&#62; Block</h3>";
string += "<table>";
for (index = 0; index <= 4; index++) {
  string += "<tr>";
  for (index2 = 0; index2 <= 3; index2++) {
    string += "<td onclick='addColor(this)' width='20%'>Click Me!</td>"
  }
  string += "</tr>";
}
string += "</table>";
document.body.innerHTML += string;
h3 {
  text-align: center;
}

table {
  margin: 0 auto;
  width: 50%;
}

table,
td {
  border: 1px solid;
  border-collapse: collapse;
}

table td {
  text-align: center;
  width: 25%;
  height: 1.5em;
}
<header>
  <img src="Fonts/Proj6_heading.png" />
</header>

<nav class="verticalNAV">
  <ul>
    <li><a href="Home_Page.html">Our Services</a></li>
    <li><a href="Growing_Pumpkins.html">Growing Pumpkins</a></li>
    <li><a href="Currency_Converter.html">Currency Converter</a></li>
    <li><a href="Add_Table_Block.html">Add Table Block</a></li>
  </ul>
</nav>

<section>
  <h2>&#60;Add Table Block&#62;</h2>

Answer №2

The initial step involves declaring an empty string called string and then appending new elements to it. Subsequently, this modified string is assigned as the innerHTML of the current page. A more effective approach would be to set the string as the existing page's innerHTML before continuing.

function generateContent(element) {
  var colors = ["green", "lightgreen", "blue", "pink", "yellow", "purple", "brown", "red", "orange", "black"];
  var index = Math.floor((Math.random() * 9) + 1);
  element.innerHTML = colors[index];
  element.style.backgroundColor = colors[index];
}

var header = document.body;

var string = `${header.innerHTML}`;
string = string + "<h3>Insert &#60;Table&#62; Block</h3>";
string = string + "<table>";
for (index = 0; index <= 4; index++) {
  string = string + "<tr>";
  for (index2 = 0; index2 <= 3; index2++) {
    string = string + "<td onclick='generateContent(this)' width='20%'>Click Me!</td>"
  }
  string = string + "</tr>";
}
string = string + "</table>";
document.body.innerHTML = string;
h3 {
  text-align: center;
}

table {
  margin: 0 auto;
  width: 50%;
}

table,
td {
  border: 1px solid;
  border-collapse: collapse;
}

table td {
  text-align: center;
  width: 25%;
  height: 1.5em;
}
<header>
  <img src="Fonts/Proj6_heading.png" />
</header>

<nav class="verticalNAV">
  <ul>
    <li><a href="Home_Page.html">Our Services</a></li>
    <li><a href="Growing_Pumpkins.html">Growing Pumpkins</a></li>
    <li><a href="Currency_Converter.html">Currency Converter</a></li>
    <li><a href="Add_Table_Block.html">Add Table Block</a></li>
  </ul>
</nav>



<section>
  <h2>&#60;Add Table Block&#62;</h2>
</section>

In addition, it is advisable to consolidate your JavaScript code into one coherent block instead of having it spread across multiple script tags as this can enhance efficiency.

Answer №3

When you want to write only on a specific section of the page, avoid overwriting the entire page with this line of code:

document.body.innerHTML = string;

Instead, use the following line to ensure you are writing only to the section element:

document.querySelector('section').innerHTML = string;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styling tables within HTML emails for Gmail and then utilizing PHPMailer to send the emails

I've been racking my brain over this for hours with no luck! Objective: Implementing inline styles for table, td, th, p elements in an HTML email intended for Gmail using PHPMailer. Challenge: Inline styles not being rendered HTML Snippet: <sec ...

ReactJS components enhanced with bootstrap-table JS extension

I recently downloaded the bootstrap-table package from NPM (npmjs.com) for my ReactJS application. It provides great features for setting up tables and datagrids. However, there are additional js and css files needed to enhance its functionality. These inc ...

Stop the bootstrap navbar from resizing

I implemented a bootstrap navbar that looks like this... <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div& ...

The functionality of CSS isn't up to snuff on Mozilla Firefox

I am having an issue with CSS styling on a <div> element in my PHP page. The CSS style is working perfectly in Google Chrome, but when I test my code in Firefox, the styling is not being applied. .due-money { background-color: #09C; color: whi ...

In an AngularJS custom filter function, the error message "keys is not defined" is displayed

As I was reviewing examples in an Angular JS book, I came across a concept that has left me puzzled. It involves the use of custom filters with ng-repeat. Below are the code snippets: <a ng-click="selectCategory()" class="btn btn-block btn-default btn- ...

The dynamic loading of videos through the YouTube API

-Need to load multiple videos onto a page, keeping it simple -Each video has an ID stored in the database accessed via $slide['message'] -Currently only loading one video successfully, others show up as blank -Code is within a loop, attempt ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

Locate the checkbox label using CSS

Is there a way to replace the standard checkboxes with font-awesome icons without modifying the generated HTML or using jQuery? EDIT: The code includes JavaScript that prevents me from making changes. Also, note that the label text class can be -1 or -2 a ...

Extracting the URL of the @font-face declaration in CSS with the use of JavaScript

Currently, my CSS file contains numerous @font-face tags. Each tag specifies a unique font-family and src URL. @font-face{ font-family: Garamond; src: url('ePrintFonts/pcl_91545.ttf'); } @font-face{ font-family: C ...

ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks: var csp = require("helmet-csp"); app.use(csp({ directives: { defaultSrc: ["'self'", "https://localhost:8000"], ...

Clicking on an element in React Material UI Autocomplete will bring it

I'm currently working with a material-ui autocomplete element <Autocomplete id="combo-box-demo" autoHighlight openOnFocus autoComplete options={this.state.products} getOptionLabel={option => option.productName} style={{ width: 300 ...

Refreshing the webpage section without requiring a full page reload

I am currently working on a Django website and I have been trying to update a specific section of the webpage without refreshing the entire page. However, most solutions I found online didn't work for me because the part I want to update is actually i ...

Is it possible to enable autocomplete for JavaScript generated code in .proto files?

I recently created a basic .proto file with the following content: syntax = "proto3"; message Event { optional string name = 1; } After downloading and installing the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) on my local machine, ...

What steps should be taken to incorporate that dynamic sliding element (like a sliding screen paper) on the webpage?

When hovering over the leftmost part of the homepage at www.techants.com, a box shifts to the foreground. I examined the code and noticed a reference to something called screen paper. Does anyone know which script is being used for this effect? How can I ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Ways to display map results in multiple columns utilizing react

I am facing a challenge and seeking guidance on how to achieve a specific layout using React. My goal is to display results in two columns as shown below: item 1 | item 4 item 2 | item 5 item 3 | item 6 I have attempted to check the array length and dete ...

Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale: var actual_JSON; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.o ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...

What is the process for generating an Electronic Program Guide for television?

Welcome to the forum! I'm a front-end developer at a company for 6 months now, currently working on a TV app. It's my first experience in this field and I'm facing some challenges, particularly with creating an epg for the app. Unfortunately ...

"What is the best way to retrieve the name of the object passed in a function in

After searching high and low, I still can't seem to find the answer to my simple question. Maybe it doesn't exist, but I won't give up just yet. So here's the scenario: I created a global prototype in Vue, essentially a global class, ...