Attempting to invoke getElementsByTagName on an already loaded SVG element would result in an error

Currently, I am facing an issue with parsing an SVG after loading it using XMLHttpRequest. The code snippet for loading the SVG is as follows:

    var svgDoc;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "data/vectors.svg", true);
    xhr.onload = function (e) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                svgDoc = xhr.responseText;
                console.log(svgDoc.getElementsByTagName("svg"));
            } else {
                console.error(xhr.statusText);
            }
        }
    };
    xhr.onerror = function (e) {
        console.error(xhr.statusText);
    };
    xhr.send(null);

An error of 'Uncaught TypeError: undefined is not a function' occurs when trying to access the `getElementsByTagName` method. Even logging `console.log(svgDoc.getElementsByTagName)` returns 'undefined'. It's perplexing since SVG is essentially XML, and yet any XML DOM methods cannot be invoked on the SVG object. What could be causing this behavior?

Answer №1

When utilizing XMLHttpRequest to retrieve the content of a remote HTML webpage, the responseText property contains a jumbled mix of all the HTML tags, making it challenging to manipulate and analyze. To effectively process this HTML soup string, there are three main approaches:

  1. Utilize the XMLHttpRequest.responseXML property.
  2. Insert the content into the body of a document fragment using fragment.body.innerHTML and navigate through the fragment's DOM.
  3. If the content of the HTML responseText is always known in advance, Regular Expressions (RegExp) can be employed. It may be necessary to eliminate line breaks when using RegExp to search for specific patterns effectively. However, relying solely on this method should be considered a last resort, as minor changes to the HTML code could cause failure.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest


In your scenario, the undefined error occurs because the responseText is merely a string and not a DOM element.

Answer №2

Hey everyone, I appreciate your input and suggestions, but after some further exploration, I've discovered an even more effective solution. Utilize a DOMParser to convert the string into a DOM object, allowing you to manipulate it using DOM methods. Here's how:

 let svgElement;
    const xhrRequest = new XMLHttpRequest();
    xhrRequest.open("GET", "data/vectors.svg", true);
    xhrRequest.onload = function () {
        if (xhrRequest.readyState === 4) {
            if (xhrRequest.status === 200) {
                const svgString = xhrRequest.responseText;
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(svgString, "text/xml");
                svgElement = xmlDoc.getElementsByTagName("svg")[0];
                console.log(svgElement);
                const viewBoxAttr = svgElement.getAttribute('viewBox').split(' ');
                offsetX = -parseInt(viewBoxAttr[2] / 2 + parseInt(viewBoxAttr[0]));
                offsetY = parseInt(viewBoxAttr[3] / 2) + parseInt(viewBoxAttr[1]);
                const sectionsXml = $(svgElement).find('g[id*="section"]');
                for (let j = 0; j < sectionsXml.length; j++){
                    const sectionElem = new section(sectionsXml[j]);
                    sectionElem.position.setX(offsetX);
                    sectionElem.position.setY(offsetY);
                    scene.add(sectionElem);
                }
            } else {
                console.error(xhrRequest.statusText);
            }
        }
    };
    xhrRequest.onerror = function () {
        console.error(xhrRequest.statusText);
    };
    xhrRequest.send(null);

Everything is in order now.

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 session disappears after redirecting using AJAX

I am currently working with an index.html login page on my local machine, which includes a JavaScript file called index.js. This file is responsible for making an ajax call to authenticate usernames and passwords against an index.php page hosted on a remot ...

What is the best way to ensure that the buttons remain in place once they have been clicked to reveal a drop-down menu?

Is there a way to keep 3 buttons inline and prevent them from moving when clicked to open a submenu? Changing their positions results in them stacking on top of each other. Any help or suggestions would be greatly appreciated, thank you! Here is the code ...

Exploring the Fundamentals of Arrays and For Loops in Javascript

Currently learning javascript on my own, with a background in C++. Stumbled upon this code snippet while studying and found the for loop structure quite peculiar: <html> <head> <script type="text/javascript> <!-- function ReadCookie( ...

How can we utilize node/express/jade to serve a specific Javascript file, depending on the availability of another file?

I've recently started developing web apps and I am facing a challenge. I have configured grunt to minify/uglify JavaScript, which works fine. However, I would like the server to check if the minified JavaScript file exists, and if it does, serve it. I ...

Extract JSON content from an array's values containing underscores

I am currently working with an array of objects and need to implement a filter on it. The objects in the list contain an owner_id property within the JSON... Currently, I am looping through all the items in the array. However, I want to exclude those wher ...

What could be causing the rejection of my authorized XML signature?

My goal is to construct a signed XML post request where the XML content needs to be included in the body of the request. The signing process must adhere to the following specifications: The digest should utilize the inclusive canonicalization algorithm Th ...

Using jQuery to retrieve the text content of child elements

Struggling to extract the text of child elements using jQuery. I've been at this for a couple of days and can't seem to make it work. If anyone could spare a moment to review, I would greatly appreciate it! SCRIPT: function generateRemoveSect ...

Executing jQuery on page update can be achieved by utilizing event handlers to trigger

I have implemented jQuery multi-select to enhance the user experience of my Django app's multiselect feature. Upon initially rendering my page, I included the following script to bind any elements with the class 'multiselect' to the jQuery m ...

Ensuring accurate parameter values for Ajax calls: the top method

I'm currently developing a website that relies on ajax calls to enhance flexibility and performance, specifically for a ranking system. The ajax calls require three input values (storeID, clientID, orderID) to be processed. To ensure that the paramete ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

Error encountered in React due to a syntax issue with parsing JSON from the response received

The structure of my node.js express server is as follows: const express = require('express'); const app = express(); const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Listening on port ${port}`)); app.get('/exp ...

Guide on crafting a JavaScript array from a PHP array using JSON and AJAX

Attempting to create a JavaScript array from a PHP array of image URLs using JSON and AJAX. The goal is to then display these images on a Cordova app. It seems that the issue lies in receiving or sending JSON messages with unintended HTML tags. When retrie ...

Is there a way for me to extract the unformatted text from a .txt file in a Discord chat using a web-based bot

Currently, I am using repl.it to host my bot. The main objective was for it to read a txt file from Discord and then upload that to a hastebin using a GitHub repository that my friend recommended to me. Unfortunately, I am facing some difficulty in extract ...

Having difficulty retrieving additional arguments within createAsyncThunk when dispatched

When attempting to update the user thunk action by passing an axios instance as an extra argument, I am encountering difficulties in accessing the extra argument. Despite being able to access other fields such as getState</coode> and <code>disp ...

Using parameters while defining an onclick event in JavaScript

After searching high and low, I finally found a solution to my problem. I have a set of buttons that are meant to remove specific table rows when clicked on. Due to the dynamic nature of the table rows, I couldn't use onclick directly in the HTML fil ...

The proper method for incorporating an async function within a for-loop

Recently, I encountered an issue while running the E2E tests after making a small change in the original test code. The change involved adding the checkColumns logic to the test script: it('check search and sort', async () => { await checkL ...

What is the best way to manage a situation when dealing with a dynamically generated button triggering a modal dialog popup and custom control?

In my custom control, there is a search function that generates a list of buttons when the user clicks search. Each button's CommandArgument property contains the Id of the search result. However, I am facing an issue where the buttons are not raising ...

Converting code from JavaScript to Python with the help of AJAX

I recently came across a discussion on the topic of ajax request to python script, where individuals were attempting to achieve exactly what I am aiming for. However, I found one crucial piece of information missing. $.post('myPythonFile.py',{da ...

A guide on displaying a JSON object using the ng-repeat directive

Looking to create a dynamic treeview menu with angularJS? Wondering how to achieve the desired results using a controller ($scope.results) and JSON data? Check out the code snippet below for an example of how to structure your treeview: <ul> < ...

Creating a Black Jack game using JavaScript document.write

I am currently in the process of developing a blackjack game using javascript. As of now, I have successfully implemented the dealer's and player's cards. However, when the player decides to draw another card, an issue arises. It seems that the d ...