How come I am unable to attach outerHTML to an element using javascript?

I am facing an issue where I am trying to move an element from one part of the page to another using JavaScript. I attempted to use the outerHTML property and the appendChild method to achieve this, but I keep encountering an error message stating that Argument 1 of Node.appendChild is not an object.

/* Here is a function for removing the overlay */
(function removeOverlay(){
document.querySelector('div.overlay span a').onclick = function()
{
document.querySelector('div.overlay').style.display ="none";
console.log('I am closing')
};

document.querySelector('div.overlay').addEventListener('click', function(){

this.style.display ="none";
console.log('Im closing with overlay');

});

})();


/* This section activates the overlay */
document.querySelector('button#overlay-on').addEventListener('click',function(){

var overlay = document.querySelector('div.overlay');
overlay.style.display = "block";

var message = document.querySelector('div#message').outerHTML;
var relative = document.querySelector('div.rela');


document.getElementById('message').setAttribute('style','position:absolute; display:block; top:10%; ');
var text = document.createTextNode(document.getElementById('message').offsetWidth);
document.querySelector('div#message p').appendChild(text);

relative.appendChild(message);
div.overlay{ height:100%; width:100%; margin:0; padding:0; background:rgba(40, 0, 77,0.7); position:fixed; z-index:100; top:0; left:0; display:none;}
    
div.rela{height:100%; width:100%; margin:0; padding:0; position:relative; z-index:101;}

div.rela span{ position:absolute; top:0; left:98%; font-weight:bold;  font-size:36px; }

div.rela span a{ color:white; text-decoration:none; z-index:152;}

div#message{width:40%; height:20%; background:white; text-align:center; border:1px solid black; font-weight:bold; display:none; z-index:102;}

div#message h5{font-size:18px;}
<div class="overlay">
  <div class="rela">

    <span><a href="#">X</a></span>
  </div><!-- end of rela -->
</div><!-- end of overlay -->

<div id="ex1"><h2>Example 1</h2><p></p><h4>results:</h4>

  <button id="overlay-on">Open up the overlay</button>

  <div id="message">
    <h5>Title</h5>
    <p>Width is:</p>
  </div><!-- end of message -->

</div>

Answer №1

appendChild requires genuine HTML nodes as its argument, which is clearly outlined in the DOM Level 3 Core documentation

In order to address this issue, you need to first create an element using the document.createElement method, like so:

(...)
var wrapper = document.createElement('div');
wrapper.innerHTML = message;
relative.appendChild(wrapper);
(...)

Answer №2

It appears that in the provided JavaScript example, you may have overlooked closing:

document.querySelector('button#overlay-on').addEventListener('click',function(){

You need to close it with:

});

After adding the closing brace, the code seems to work fine. Could this be the issue, or could there be a cross-browser compatibility problem?

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

Numerous error notifications triggered by a different data field

I attempted to create a dynamic error message: window.Parsley.addValidator('validatorName', { requirementType: 'string', validateString: function (value) { return validateField(value); }, messages: { en: &apo ...

What is the best way to conceal the broken image icon using PHP?

UPLOAD PICTURES IN DATABASE: if (!isset($_FILES['gambarid']['tmp_name'])) { echo ""; }else{ $rand5=rand(); $image_name5= addslashes($_FILES['gambarid']['name']); $fileext5=explode('.&ap ...

What is the best way to organize columns on the front end?

A table needs to be displayed on the front end with the following code snippet: <logic:present name="searchStudent"> <table class=" tblSearchResult" border="1" cellspacing="0" cellpadding="0"&g ...

connect a column from a separate array in pdfmake

In my current project, I am looking to link the values of an array that is different from the one present in the initial two columns. Is this achievable? (The number of partialPrice values aligns with the number of code entries). Despite several attempts ...

What is the process of setting a TypeScript variable to any attribute value?

I have a variable declared in my TypeScript file public variableName: something; I want to use this variable to replace the value of custom attributes in my HTML code <input type="radio" name="someName" id="someId" data-st ...

Decorative initials have a tendency to create spaces within the text

I have incorporated Google Fonts into my website, along with Bootstrap. Here is the code I am using: .initial { font-size: 1.5em; font-family: 'Euphoria Script', cursive; } p { font-family: 'Open Sans', sans-serif; } <html> ...

`There is a delay in rendering the background image on Chrome`

Once I apply a class to my button element using JavaScript, the background image (.gif) that is supposed to display afterwards takes an unusually long time to render. The button serves as a form submission. Upon being clicked, a class of "clicked" is dyna ...

Can the target for orbit controls be set by clicking the mouse?

In my attempt to configure the orbit controls target in three.js, I encounter a challenge. For instance, when using , the camera consistently revolves around the center of the model unless the camera is panned. The desired behavior from the orbit controls ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Get rid of emojis and unicode characters

My website and database are both configured to utf-8 and utf8mb4 encoding. While textareas accept utf-8 symbols and emojis without issue, I want to restrict certain input fields (such as name and address) to only allow basic text and numbers. This include ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

Guide on showcasing jQuery variable values in PHP on a single page

I have some JavaScript and PHP code that I need help with. I want to assign a jQuery variable value to a PHP variable called $nicks, and then echo the value of $nicks on the same page. <script type="text/javascript"> var axel = 131.5678466; < ...

Optimizing User Addition in Python Using Selenium

Currently, I am developing test cases to populate a new web app account with multiple users simultaneously. Here is the script I am using: driver.find_element_by_css_selector("input.ss-med.small").clear() driver.find_element_by_css_selector("input ...

Deployment replacement in Kubernetes encounters error

I've developed a NodeJS script to deploy review apps to Kubernetes for my GitLab repository, using the Kubernetes NodeJS client. Including abbreviated definitions of Kubernetes resources for thoroughness: const k8s = require('@kubernetes/client ...

Sizing labels for responsive bar charts with chart.js

I'm encountering a problem with my bar chart created using chart.js - the responsive feature works well for some elements but not all. Specifically, the labels on my bar chart do not resize along with the window, resulting in a strange look at smaller ...

Discovering relative URLs within an MVC 4 framework

Seeking a solution for storing the fully qualified URL of a relative path in MVC: ~/Content/themes/base/jquery-ui.min.css" In my scenario, I have a hidden input field: <input type="hidden" id="siteUrl" value=""/> I attempted to populate this hidd ...

Transforming the Bootstrap 3 Carousel into a fixed image with overlaying sliding text

I am interested in creating a Carousel that features a single static image with text sliding over it, instead of multiple images changing with the text. For example, when clicking the next slide button, only the text will move while the image remains stat ...

Button hyperlink

I'm working on a new 'tour' page that will showcase the dates for upcoming shows. I would like to include a button on the page that, when clicked, will display the number of available tickets and provide an option to purchase them. I am also ...

Changing the name of a specific attribute in a JSON Object for showcasing it in an HTML Table

Suppose I have fetched a list of objects from a database: [{ "id":0 ,"name":"John", "lastname":"Shell" },{ "id":1,...]; and want to display this data using the dynatable plugin: data : JSON.stringify(data) success: function(data,status){ $( ...

The ASP.NET JSON response unexpectedly contained undefined data

I am working on a straightforward web application that features a HouseUnitController containing an action that delivers a JSONResult. public JsonResult GetHouseUnits() { var houseUnits = db.HouseUnits.Include(h => h.HouseModel).Include(h = ...