``I am experiencing an issue with HttpXMLRequest becoming un

I am currently experimenting with the HttpXMLRequest object in JS and have created a basic loop that retrieves name and age data from an XML file to display in a table. The issue I am facing is that if one of the elements is missing from a sibling, the code stops running instead of skipping it. Here is an example of the code:

The HTML -

(The rest of the XML parser and DTD, html, body etc is up here)
<script>
var x=xmlDoc.getElementsByTagName("person");

document.write("<table border='1'>");
for (i=0;i<x.length;i++)
  { 
  var name = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
  var age = x[i].getElementsByTagName("age")[0].childNodes[0].nodeValue;

  document.write("<tr>");
  document.write("<td>"+name+"</td>");
  document.write("<td>"+age+"</td>");
  document.write("</tr>");
  }
document.write("</table>");
</script>

The XML -

(The DTD and stuff it up here)
<people>
  <person>
    <name>Jim</name>
    <age>20</age>
  </person>
  <person>
    <name>Bob</name>
  </person>
  <person>
    <name>Tom</name>
    <age>20</age>
  </person>
  <person>
    <name>James</name>
    <age>20</age>
  </person>
  <person>
    <name>Richie</name>
    <age>20</age>
  </person>
</people>

As shown in the example above, the HTML code stops after writing "Bob". I believe there needs to be some sort of error handling mechanism such as try/catch or an if statement for each name and age value, but I'm struggling to implement it effectively. Does anyone have any suggestions?

I have attempted to research this issue, but without knowing what it is called, I am not finding relevant information.

Simply inserting "<age /> or <age></age>" as placeholders is not viable since I will be working with large XML files in the future. If necessary, I am open to creating a function that automatically adds the missing element if it does not exist.

Thank you, Hombries.

Answer №1

Make sure to check for the existence of an element before attempting to access its child nodes:

var personElem = x[i];

var ageElems = personElem.getElementsByTagName("age");

var age = ageElems.length
        ? ageElems[0].firstChild.nodeValue
        : '';

Additionally, consider using JSON instead of XML as it is generally easier to work with. With JSON, your data structure could look like this:

{
    "people": [
        {
            "name": "Jim",
            "age": 20
        },
        {
            "name": "Bob"
        }
    ]
}

You can then access elements using dot syntax:

var age = data.people[0].age;

For instance, PHP offers a built-in function for encoding JSON: json_encode().

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

The ASPX validation will not be able to access the .js file

I am facing an issue with client-side validation using JavaScript (.js). Despite linking the path in the head section, the ASP file doesn't seem to reach the JavaScript file. <head runat="server"> <meta http-equiv="Content-Type" content="tex ...

Tips for choosing a loaded element using the jQuery load() method

I am currently facing a challenge with the following (here is a snippet of code to illustrate): <div id="container"></div> <script type="text/javascript"> $('#container').load('content.html'); $('.eleme ...

Add a CSS file to the browser-sync with proxy functionality

Currently, I have a script that I utilize to proxy a live website in order to make CSS modifications. Instead of replacing the online CSS file with a local one using a rewrite, I am exploring the possibility of injecting an entirely new file below the exis ...

What is the mechanism behind the functionality of the input type=number spinner in browsers?

I want to recreate the spinner feature found in input type=number. <input type=number step=0.3/> When clicking on the up arrow of the spinner, the value increases by 0.3 (0.3, 0.6 , 0.9 , 1.2 , 1.5 ...etc). However, if the current value is 1.4 and ...

Clearing the Redux state in my app upon exiting the page

I've come across similar inquiries, but none of them quite match my situation. When a user clicks on one of the buttons in my app, it triggers a get request to fetch data and then displays that data on the screen. However, the issue arises when I nav ...

Utilize JavaScript to establish an object with key and value pairings

Wanting to loop through and create an object that contains key => [value], if the key already exists, simply add the value. Here is what I have tried so far: let dataName = []; let obj = {}; checkboxes.forEach(checkbox => { if (checkbox.che ...

Find the nearest element with a specific class using jQuery

I am currently using jQuery version 1.12.4 for the purpose of retrieving the value from the closest element with a specific class selector. Unfortunately, I am encountering difficulty in selecting the closest element as desired. $(function() { $("[cla ...

Error message from BitBucket pipeline indicates that the npm command was not found

Upon deploying code to my server via the Bit Bucket scp pipeline, I encountered an issue with another pipeline meant to install node modules and start the node server. The pipeline returned a failed status and displayed the following error: ./server-run.s ...

Traversing an array of objects to extract and display the key-value pairs for each object

Here is an array I am working with: const cuisines = [ { african: "African" }, { american: "American" }, { arabian: "Arabian" }, { argentine: "Argentine" }, { asian: "Asian" }, { asian_fusion: "Asian Fusion" }, { australian: "Australi ...

JSHow to dynamically access child elements in objects

I am facing a challenge in dynamically accessing a JSObject item: jsonElement = { name:"name", subElement { subElementName: "nameSubElement", } } Currently, I have the element as: //level = "name" jsonElement[level] -> it works //lev ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...

What is the best way to tally data-ids within an anchor tag using jQuery or plain JavaScript?

find total number of data-id attributes within tag a I am looking for a way to calculate the count of my id attribute, whether it is in data-id or another form, using JavaScript. Edit ...

locate the presence of a specific letter within a sequence of characters

When dealing with strings like "Galley1", "Galley2", "Galley3", "Galley4", "Galley5", "Galley6" up to "Galley20", the task is to determine whether a condition is met. The condition should return true if the string contains a number between 1 and 7, inclusi ...

Array in JavaScript containing a replica set of Node.js and MongoDB

As a novice programmer with more experience in sysadmin work, I've been tasked with setting up a new HA environment for a node js application using MongoDB. The current setup utilizes mongojs and monq java classes with only one MongoDB instance. In or ...

Having Trouble Accessing Custom Screen in React Navigation?

The navigation from the Order screen to the Home Screen is not working as expected. Every screen in the route works, except for the Home screen, which just navigates back to the Map screen. I have clearly instructed to navigate to Home. Here is the curren ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

What is the best way to leverage multiple random YouTube v3 API keys simultaneously?

I have the following code snippet and I am looking to randomly select an API key from a list of keys: function search() { // Clear Results $('#results').html(''); $('#buttons').html(''); // Get Form Input ...

"Generating a unique, random HEX color using JavaScript from an array

Currently, I am attempting to create a random border color within a div using specific hex codes that have already been determined, but I am encountering some difficulties. Does anyone have any suggestions on how to achieve this? I am still learning JavaS ...

Executing javascript code that has been inserted into inner HTML is not functioning as expected

Trying to retrieve a response from another page, specifically named ajaxresponse.php, through an AJAX request. I also aim to execute some JavaScript actions on that ajaxresponse.php page, but the JavaScript code is not functioning as expected. Although I a ...

"Customize your map pins on Google Maps by updating the marker location through a

I am trying to update the position of a map marker based on a dropdown selection. Upon changing the dropdown option, I retrieve the latitude and longitude values and want to set these coordinates for my current marker. Here is the code snippet: $("#locati ...