When JavaScript is used to create HTML elements, they mysteriously vanish

I've encountered another issue after resolving the previous one

XML file reading problem: always the same result

While dynamically creating HTML elements and assigning values read from an XML file, the elements disappear right after creation. Any insights on why this might be happening? Below is the code snippet from my C# file:


script = "function OnClientDragEnd(dock, args)" +
                            "{" +                    
                            "   req = false; " +
                            "   var isIE = false;" +
                    // branch for native XMLHttpRequest object
                            "   if(window.XMLHttpRequest && !(window.ActiveXObject)) {" +
                            "       try {" +
                            "           req = new XMLHttpRequest();" +
                            "       } catch(e) {" +
                            "           req = false;" +
                            "       }" +
                    // branch for IE/Windows ActiveX version
                            "   } else if(window.ActiveXObject) {" +
                            "       try {" +
                            "           req = new ActiveXObject('Msxml2.XMLHTTP');" +
                            "       } catch(e) {" +
                            "           try {" +
                            "               req = new ActiveXObject('Microsoft.XMLHTTP');" +
                            "           } catch(e) {" +
                            "               req = false;" +
                            "           }" +
                            "       }" +
                            "   }" +
                            "   if(req) {" +
                            "       req.onreadystatechange = function(){processReqChange(dock,args)};" +
                            "       req.open('GET', 'Config.xml', false);" +
                            "       req.send('');" +
                            "   }" +
                            "}" +
                            "function processReqChange(dock,args) {" +
                                // only if req shows "loaded"
                            "   if (req.readyState == 4) {" +
                                    // only if "OK"
                            "       if (req.status == 200) {" +
                                    // ...processing statements go here...
                            "           var contagemNos = req.responseXML.documentElement;" +
                            "                           var txt = contagemNos.childNodes(i).getElementsByTagName('Titulo')[0].text;" +//alert(txt);
                    "                           var ta = contagemNos.childNodes(i).getElementsByTagName('Id')[0].previousSibling; var tatext = ta.text;" +//alert(tatext);
                    "                           var ni = document.getElementById('spanObjDock');" +
                    "                           var divIdName = 'myDiv';" +
                    "                           var newdiv = document.createElement('div');" +
                    "                           newdiv.setAttribute('id',divIdName);" +
                    "                           var labelTitulo = document.createElement('label');" +
                    "                           labelTitulo.id = 'span1';" +
                    "                           labelTitulo.innerHTML = 'Title';" +
                    "                           newdiv.appendChild(labelTitulo);" +
                    "                           var break1 = document.createElement('br');" +
                    "                           newdiv.appendChild(break1);" +
                    "                           var tboxTitulo = document.createElement('input');" +
                    "                           tboxTitulo.setAttribute('type', 'text');" +
                    "                           tboxTitulo.setAttribute('value', txt);" +
                    "                           tboxTitulo.setAttribute('name', 'tboxTitulo');" +
                    "                           tboxTitulo.setAttribute('id', 'tboxTitulo');" +
                    "                           if (tboxTitulo.addEventListener){" +
                    "                               var enviar = 'tboxTitulo';" +
                    "                               tboxTitulo.addEventListener('keyup', function(){updateValueTitulo(enviar);}, false);" +
                    "                           } else if (tboxTitulo.attachEvent){ " +
                    "                               var enviar = 'tboxTitulo';" +
                    "                               tboxTitulo.attachEvent('onkeyup', function(){updateValueTitulo(enviar);});" +
                    "                           }" +
                    "                           newdiv.appendChild(tboxTitulo);" +
                    "                           var break1 = document.createElement('br');" +
                    "                           newdiv.appendChild(break1);" +
                    "                           ni.appendChild(newdiv);" +   
                            "       } else {" +
                            "           alert('There was a problem retrieving the XML data: ' + req.statusText);" +
                            "       }" +
                            "   }" +
                            "}";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "PositionChanged", script, true);

This snippet shows the code in my ASP.NET file:

....
<asp:UpdatePanel runat="server" id="UpdatePanel3">
        <ContentTemplate>                
            <div id="spanObjDock"></div>
        </ContentTemplate>        
</asp:UpdatePanel>
....

Answer №1

Here are two recommendations that may help:

  1. Consider using jQuery (or a similar library, with jQuery being supported by MS and offering Intellisense). Much of the code you've shared could be simplified with jQuery, allowing you to focus on your application logic without worrying about cross-browser compatibility.
  2. Try debugging your code using Firefox + Firebug. You can set breakpoints and run your code step by step to pinpoint where changes to your HTML are reverting.

Check out these links for more information:

jQuery: http://jquery.com/

Firebug:

Using jQuery in Visual Studio 2008:

jQuery tutorials: http://docs.jquery.com/Tutorials

jQuery .get() method: http://api.jquery.com/jQuery.get/

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

What is the reason behind having 3 watchers for 1 binding in AngularJS?

Take a moment to view the screenshot provided below https://i.sstatic.net/qLcem.png In the screenshot, it is evident that there are #3 watchers for a single binding. Would someone care to explain the reason behind this? P.S: I am utilizing AngularJS Ba ...

The callback within an Angular directive is triggered before the model is updated

There is an issue with a directive that has a model and callback mapped to the parent scope. The problem arises when the parent model is updated after the callback has occurred, even though in the code it is assigned before. DEMO: PLUNKER (Click twice or ...

Using JavaScript/JQuery to Access an External SQLite Database

Is there a way to incorporate my own SQLite database into a website using JavaScript and JQuery? I've searched for examples but have yet to find any helpful articles on the topic! ...

Implementing the "or" operator in Mongoose: A guide

I have two schemas, one for projects and the other for users A user can create multiple projects The user schema is as follows: { Name: String, Pass: string, } Project schema : { ProjectName: String, members : [ {type: ObjectId, ref : ' ...

The pagingParamsProvider is not recognized in the ResultAnalysisDetailController, which is causing an error

My generated controller is causing an issue with the pagingParams injection. Although other jhipster controllers work fine, mine throws an error for unknown provider. (function() { 'use strict'; angular .module('netCopOnlin ...

What is the correct method for notifying the progress of time using jQuery?

I'm looking for a way to display the processing time of my PHP code using jQuery Here's an example of my PHP code : <?php //some queries to database ?> Below is my jQuery code: $.ajax({ type: "POST", url: "action. ...

Unable to extract the 'id' property from 'params' object in Next.js 13.4 due to its undefined value

I am currently trying to retrieve the [id] URL parameter in Next.js 13.4, but I keep encountering an error stating that params is undefined. Despite extensive online research and seeking assistance from ChatGPT, all I could find were examples for older ve ...

Storing a Mongoose value as a date: best practices

Whenever I store a date in Mongoose, it always gets saved as a string. let currentDate = new Date().toISOString(); let item = await Item.findOne({}); item.details.expiryDate = currentDate; await item.save(); After checking the database ...

When the action "X" was executed, reducer "Y" resulted in an undefined value

I'm encountering an issue with Redux in React. Despite searching through related questions, I haven't found a solution that fits my specific case. Here are the files involved: Index.JS import snackbarContentReducer from '../src/shared/red ...

Steps to deactivate a div in React after a single click

When you click the "show" button for the first time, it displays "hello world" correctly. However, if you click on show again, it should not work. How can I make it so that after one click, it does not hide hello world if you click again? I've tried u ...

Icon positioned to the left within the text box

Hey there! I'm new to NativeScript and I've been struggling to place an icon inside a textbox. Can someone please help me out? Expected Output: https://i.stack.imgur.com/xvoZG.png Code <GridLayout columns="*, *" rows=& ...

Cross-Domain Image Uploading

I've been attempting to enable image uploads from one domain to another (CORS). Everything runs smoothly on Localhost, but when I try it on an actual domain, I consistently encounter this message in the Developer Console: Invalid request In my uplo ...

Converting C# DateTime to JavaScript DateTime

Currently, I am utilizing the code below to send information to my Javascript code: sb.Append("start: new Date(" + Convert.ToDateTime(appointment.AppointmentDate).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString() + "),"); However, I am faci ...

Understanding the relationship between Ajax callbacks and variable scope while importing JSON data into an array

I am using ajax to load a geoJSON file with the goal of pushing the coordinates of a MultiPoint feature into a global array for later use. I am encountering an issue with my callback function in the given code snippet. The intention here is to read the da ...

What is causing my basic angularjs to not function properly?

In my angularjs test instance, I am using a global variable but the alert tag is not functioning as expected. This code snippet is from my first example on codeschool. Any thoughts on why the alert is not running? <!DOCTYPE html> <html xmlns="ht ...

Remaking the functionality of jQuery's $.ajax() method while utilizing the .done() method

As a junior javascript developer, I am working on creating my own "basic" javascript framework inspired by jQuery. I am particularly fond of method chaining instead of callbacks, but I am finding it challenging to implement this. Currently, I have develop ...

What is the importance of using a polyfill in Babel instead of automatically transpiling certain methods?

Recently, I have been diving into a course that delves into the use of babel in JavaScript. It was explained to me that babel, with the preset "env," is able to transpile newer versions of ES into ES5. However, I found myself facing a situation where the a ...

Avoid subscribing to the Observable fromEvent in certain conditions

I need to implement a functionality to skip or ignore the subscription on the fromEvent() observable when a specific condition is met: if this.currentPosition === this.vc.getScrollPosition()[1], I do not want to subscribe to the observable. This is beca ...

Retrieving information from MongoDB for a specific ObjectID associated with the current authenticated user

Having two collections in my MongoDB structured as follows: Data User: id: ObjectId ("5fb39e3d11eaad3e30cfb1b0") userName: "Tobias" password: "yyy" id: ObjectId ("5fb3c83fb774ff3340482250") userName: "Thor&qu ...

Achieving proper variable-string equality in Angular.js

In my Angular.js application, I am utilizing data from a GET Request as shown below. var app = angular.module('Saidas',[]); app.controller('Status', function($scope, $http, $interval) { $interval(function(){ ...