The combination of "object HTMLDivElement" with outerHTML and replaceWith() yields no results

I can't seem to figure out why this code is failing. I'm attempting to replace a DIV entirely using replaceWith from jQuery.

I've tried multiple variations, but nothing seems to work. When I try outerHTML instead of html, I get [object HTMLDivElement] (which indicates that I'm working with a node, right? So replaceWith() should work?).

I'm looping through an array of currently displayed 'cardObjects' and comparing it to an incoming array with the same structure (it's a sorted ordered list). The object's html is the node element, and the object's target is pointing to the element's id.


function cardConstructor(item)
{
  var cardDiv = constructElement('div', "queCard", "machine"+item.machineID+"ID"+item.ID, "");
  //more html stuff gets appended to this element, but not relevant for problem
  cardObject = 
  {
    ID: item.ID,
    machineID: item.machineID, 
    lastID: item.lastID, 
    nextID: item.nextID, 
    jobID: item.jobID,
    target: cardDiv.id, //string
    html: cardDiv //node

  }
  return cardObject;
}
// here is where the problem is - 
// it is in an update loop, 
// this is failing
else if(inc[y].ID != current[y].ID)
{
  console.log("ids do not match, splicing and replacing");
  console.log("current y target is:");
  console.log(current[y].target); //334 ---console output
  var updateTarget = document.getElementById(current[y].target);

  console.log("old html"); //337
  console.log(updateTarget); //338
  console.log("new html"); //339
  console.log(inc[y].html); //340

  updateTarget.replaceWith(inc[y].html); 
  console.log("update target updated: as"); //343
  console.log(updateTarget);   //344
  current.splice(y,1, inc[y]);

}

The console.log output is:

current y target is:
machinewindow.php:334 machine1ID775
machinewindow.php:337 old html

machinewindow.php:338 <div class=​"queCard" id=​"machine1ID775">​<div class=​"queCardTitle" id=​"Titlemachine1ID775">​<div class=​"itter" id=​"itterDiv+1machine1ID775">​1​</div>​<button class=​"completeBtn" id=​"complete775" value=​"775">​complete​</button>​</div>​<div class=​"queCardBody" id=​"Bodymachine1ID775">​…​</div>​<div class=​"queCardFooterW" id=​"queCardFooterWmachine1ID775">​…​</div>​</div>​

machinewindow.php:339 new html

machinewindow.php:340 <div class=​"queCard" id=​"machine1ID774">​<div class=​"queCardTitle" id=​"Titlemachine1ID774">​…​</div>​<div class=​"queCardBody" id=​"Bodymachine1ID774">​…​</div>​<div class=​"queCardFooterW" id=​"queCardFooterWmachine1ID774">​…​</div>​</div>​

machinewindow.php:343 update target updated: as

machinewindow.php:344 <div class=​"queCard" id=​"machine1ID775">​<div class=​"queCardTitle" id=​"Titlemachine1ID775">​…​</div>​<div class=​"queCardBody" id=​"Bodymachine1ID775">​…​</div>​<div class=​"queCardFooterW" id=​"queCardFooterWmachine1ID775">​…​</div>​</div>​

As shown in the console.log, the div does not get updated. If I try updateTarget.outerHTML = inc[y].html instead, I get [object HTMLDivElement] on the browser window.

I've attempted multiple iterations, and I'm a bit confused as to why this isn't working. The object's html is a node, but it won't replace another node with replaceWith();

I'm sure I'm overlooking something.

Also, below is the constructElement function as requested.


function constructElement(element, styleClass, type, data)
{
  var ele = document.createElement(element);
  ele.setAttribute("class", styleClass);
  ele.setAttribute("id", type);
  ele.innerHTML = data; 
  return ele;
}

Answer №1

To incorporate the

updateTarget.replaceWith(inc[y].html);

substitute line 335 with:
var updateTarget = $(current[y].target);

since replaceWith is a jQuery method that should be used with a jQuery object.

If you opt for using outerHTML, ensure that you have an HTML string (not a node) on the right side, for example:

updateTarget.outerHTML = "<div>blah blah</div>";

or in your scenario:

updateTarget.outerHTML = inc[y].html.outerHTML;

Trust this offers some clarity and assistance.

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

Scroll Bar Menu (User-Controlled)

I'm looking for any libraries out there that can replicate or provide a similar horizontal scrolling menu to that of espn.com's homepage. I'm relatively new to jquery and feeling a bit lost on where to begin. I did some searching on Google, ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...

Unable to retrieve the string contained within an element - JavaScript object literal

I am currently facing an issue where I am attempting to retrieve the text content of two div elements with classes .class-date and .class-time, but I keep encountering an Uncaught TypeError stating "e.siblings is not a function". I believe this may be a ...

Tips on passing methods to form provider with unique name for managing nested forms

As discussed in #60277873, when creating nested forms, it is necessary to rename the methods of the nested form as follows: const { register, formState: { errors }, handleSubmit, } = useForm({ mode: "onBlur", }); This code sh ...

Convert JavaScript back into an HTML attribute

Is there a way to include a JavaScript code in an HTML attribute like shown below? <div class="xx" animation="yy" animate-duration="<script>Code goes here<script>" ...> </div> I'm struggling to figure it out, is there a solut ...

JQUERY inArray failing to find a match

I'm at my wit's end working with inArray and I'm really hoping for some help. I am using AJAX to fetch userIDs from my database, which come through as a JSON-encoded array. However, no matter what I try, I always get a -1 when trying to mat ...

Code snippet: Retrieve the previous and upcoming events based on the current date from an array (JavaScript/Angular)

Is there anyone who can assist me with an algorithm? I have a list of events and need to retrieve the next event and previous events based on the current date. For example: I fetch all events from an SQL database like so: events = [ {eventId:1, event ...

Accordion checkbox with dynamic features

Currently, I am dynamically populating data into a jQuery accordion. My goal is to include a checkbox just before the <h2> text. <div id="checkbox"> <h2> <span> <input type="checkbox" class="mycheck" value="apple" / ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

The form submission button fails to function when the onsubmit function returns false

When submitting, I check two fields. If one of the two fields is checked, then I return true; otherwise, I return false. The issue I'm facing is that even when I check one of the checkboxes, the submit button does not seem to work (I use console.log() ...

Press the "Reveal More" button to expand the content to its full size

I am currently working on coding a "read more" section using a button. I have looked at some existing solutions, but none of them are to my liking. My plan is to create a div that includes all the relevant content. My goal is to have a div at the bottom w ...

Using the combination of PHP and AJAX, modify files in real-time

Looking to dynamically change files based on screen resolution, I have three files: index.php main.js testA.php testB.php The index.php file will dynamically call testA and testB. If the screen resolution is desktop size, index.php should include testA ...

The management of jQuery events through .on and .off functions, maintaining the correct order, and ensuring their

Check out this jsFiddle example: http://jsfiddle.net/fThMa/2/ By clicking inside the note or rend text fields and then double clicking any of the 4 TDs below, you can insert the appropriate HTML entities into the note or rend text fields. This also includ ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

Tips for interacting with a custom web component using Selenium WebDriver

As a newcomer to writing selenium tests, I am attempting to create an automated test for a carousel feature on our homepage. The objective is to click on one of the carousel navigation buttons and then confirm that a specific inline style has been applied ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...

Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading. Here is the factory code I am using: var map = false; var myLatlng = new google.maps.LatLng(48.6908333333 ...

Guidance that utilizes the scope of a specific instance

I have successfully created a d3.js directive, but I am facing an issue when resizing the window. The values of my first directive seem to be taking on the values of my second directive. How can I separate the two in order to resize them correctly? (both ...

Does the entire window fade before the URL is loaded?

Is it feasible for me to create an effect where, upon a user clicking on a link, the entire window fades out (perhaps with a black div covering it), and then loads an external URL like 'google'? For example: User clicks 'Here', and th ...

Trigger the ASP .NET OnCheckedChange server event using JavaScript

One issue I encountered is related to a checkbox with an OnCheckedChanged event. Occasionally, I modify the checked status of the checkbox using javascript. However, when this occurs, the OnCheckedChanged event does not trigger. Is there any method to ens ...