An HTML button generated by a .js file is able to execute a .js function without any issues, but it inadvertently removes all .css styling

Currently grappling with an issue in my JavaScript self-teaching journey that I can't seem to resolve or find examples for.

The problem at hand: When the HTML button calls a .js function, it successfully executes the function but also wipes out all CSS formatting on the page.

Here's the context:

  • I have an HTML file that incorporates CSS (working fine)
  • The HTML file loads a JavaScript file (also working fine)
  • The JavaScript file creates a button in the HTML (functioning as expected)
  • When the button calls a JavaScript function, it works but messes up all the CSS styling

Any ideas on how to tackle this? Thank you!

var button = document.createElement("button");
button.innerHTML = "Press Me";

var body = document.getElementsByTagName("body")[0];

body.appendChild(button);

button.addEventListener("click", function() {
    Main();
});

Here is the complete JavaScript code:

const myHeading = document.querySelector('h1');
myHeading.fontFamily = "courier";
myHeading.textContent = "Welcome!";

Main:
Main();
  
Functions:
function Main() {
    DisplayStuff();
    DisplayUI();
}
function DisplayStuff() {
    WriteMe ("Hello!");
}

function DisplayUI(){
    //Buttons
    var button = document.createElement("button");
    button.innerHTML = "Press Me";

    var body = document.getElementsByTagName("body")[0];
    body.appendChild(button);

    button.addEventListener ("click", function() {
       Main();
    });
}

function WriteMe(x) { 
    var R = "<br>"; 
    document.write(x + R);
} 

Answer №1

By abandoning the use of document.write(), I was able to prevent the eradication of all CSS styles on the webpage. Instead, I devised a method to input text directly onto the page without affecting the CSS. Utilizing a table's .innerHTML property allowed me to achieve this successfully.

myTable.rows[r].cells.item(c).innerHTML = h1.textContent

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

Issue encountered when submitting form: Error identified as "Unexpected string expression without template curly in string"

As a novice in React.js, I am facing an issue where setState is not functioning properly when submitting a form. Any suggestions on how to resolve this problem? > class Home extends Component{ constructor(props){ > super(props) > ...

When you use the useState object in NextJS, the context object may appear to be empty

I've encountered an issue while trying to pass a context object in NextJS that uses data from a useState hook. Strangely, the state variable and setState functions are undefined when consumed. It's puzzling because substituting a simple variable ...

Certain mobile devices experiencing issues with AngularJS filters

Currently, I am attempting to filter an AngularJS array by utilizing custom filters within a controller. The filters are functioning correctly on certain mobile devices, yet they are not working on others. Here is the code snippet that I am using: var a ...

Transform numbers into elements of an array and replace undefined with an empty array

Check out this Plunker example where a filter is implemented to allow select box options to be selected only once: http://plnkr.co/edit/BBqnTlxobUpiYxfhyJuj?p=preview .filter('arrayDiff', function() { return function(array, diff) { console.log ...

Update the month in the second date picker to align with the selection made in the first date picker within the Angular framework

Is it possible to dynamically change the month of the second datepicker based on the selection made in the first date picker? Currently, it is displaying the current date by default. For example: If I select 15-10-2104 from the first date picker, the secon ...

Struggling to perfectly align text in the middle of a div container that also has

Seeking help with aligning text vertically within a div that also contains an image. Previous attempts with CSS properties like vertical-align: center; and line-height:90px have proven ineffective. Removing the image allows for the successful use of line- ...

The art of selecting elements and attaching event listeners in a React environment

Currently, I am working on my portfolio website using Gatsby. The layout includes a sidebar on the left with navigational links (Home, About, Work, etc.), and the main content is displayed as one long strip of sections on the right. When a user clicks on a ...

Delete an element once the ajax request is complete

After closing the modal, I noticed that a div element was left behind causing the screen to become unresponsive. <div class="modal-backdrop fade show"></div> I found that removing this element using the console command below fixed the issue: ...

Transferring a parameter from link_to to a popup window in a Rails application

I am facing an issue with passing an object to my modal in Rails. The object has a table of results with an attribute "email", but I seem unable to pass it so that I can use it within my modal. index.html.erb <div class="modal fade bs-example-modal-lg ...

Encountering a compilation error when attempting to import a shader from a file in a project using THREE.js, Vue.js

I've encountered an error and spent hours searching for a solution, but unfortunately found nothing. The correct way to import shader code from a file is: import {ColourShader} from '../shaders/ColourShader.js' Here is the content of my &a ...

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

Nuxt encountered an issue with Vue hydration: "Tried to hydrate existing markup, but the container is empty. Resorting to full mount instead."

I'm facing an issue while trying to integrate SSR into my project. I keep encountering this error/warning. How can I pinpoint the problem in my code? There are numerous components in my project, so I'm unsure if I should share all of my code, b ...

How to clear a particular select option in react-bootstrap

I am looking for a solution to clear the second select when the first one selects option B. The clearing should involve removing the value, disabling it, and setting the default option to Select.... import React, { useState } from "react"; import ...

What is the best way to make a hyperlink in HTML open in the same page or window, without relying on the <iframe> tag or JavaScript?

I have two html files and one css file. My question is how to open the link monday.html on the same page or window in my content section. For example, when someone clicks on the Monday navigation button, I want the result to show up in the content section ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Creating interactive button groups with responsive design in a Material UI and ReactJS web application

Is it possible to make ButtonGroup Buttons responsive? I heard about an attribute called "Orientation" in material-ui's ButtonGroup, but I'm not sure how to use it with media queries for changing orientation based on the device width. I'm st ...

Transitioning from left to right, picture smoothly scrolls into view using Way

I've explored various websites and even attempted to decipher a waypoint guide, but unfortunately, I haven't had any success. The scroll function doesn't seem to be working with the code below. (source: ) Any assistance on this matter would ...

The collapsible menu is not expanding properly after a click event due to the small size of

My website has a menu placed in the header with a background color. When resizing the page (max width 1044 px), it switches to a mobile menu, but the div holding the menu and anchors is too small compared to the header. Is there a solution to this issue? ...

Even with manual installation, the npm package still encounters dependency errors

Having trouble implementing the Imgur package from NPM into my Angular web app. The installation and import seemed to go smoothly, but when initializing a variable with the package, I encounter compile errors pointing to missing dependencies like 'cry ...

Adding a class to a div upon loading: A guide

Currently using the following script: $(document).ready(function() { $(".accept").change(function () { if ($(this).val() == "0") { $(".generateBtn").addClass("disable"); } else { $(".generateBtn").remove("dis ...