Updating the content of an SVG file in real-time

I have an SVG file saved externally that includes the following code:

<g
     inkscape:groupmode="layer"
     id="layer9"
     inkscape:label="score"
     style="display:inline">
     <text
        xml:space="preserve"
        style="font-style:normal;font-weight:normal;font-size:22.5px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
        x="100.3568906"
        y="20.353357"
          id="text5833"
        sodipodi:linespacing="125%"><tspan
          sodipodi:role="line"
          id="tspan5834"
          x="300.3568906"
          y="20.353357">Score</tspan></text>
  </g>

I am attempting to dynamically update the text "Score" using a JavaScript file, but so far I haven't been successful.

This is what I have tried:

var list = layerNamed('score').getElementsByTagName("g");
var textNode = document.createTextNode("Score:-1");
list.appendChild(textNode);

Answer №1

If you want to modify the content of an existing text element, you can do so using the code snippet below.

document.getElementById('textid').textContent = "new text";

Check out this demo:

function updateText()
{
  document.getElementById('textid').textContent = "new text";
}
<svg height="30" width="200>
  <text id="textid" x="0" y="15" fill="red">I love SVG!</text>
  Sorry, your browser does not support inline SVG.
</svg>

<button onclick="updateText()">Click here to update text</button>

Answer №2

It appears that there are a couple of issues in your code.

1) The line

layerNamed('score').getElementsByTagName("g")
retrieves all elements with the specified tag name and returns them as a NodeList object. Remember that NodeList indexes start at 0, so to access the first element, you should use the following code:

var list = layerNamed('score').getElementsByTagName("g")[0];

2) Instead of adding a new text element to update the content, you can directly access the text and tspan elements to modify the text content of tspan like this:

var textNode = list.getElementsByTagName("text")[0].children[0];
textNode.textContent = "New Text";

var list = document.getElementsByTagName("g")[0]; //document.getElementById("#layer9");
var textNode = list.getElementsByTagName("text")[0].children[0];
textNode.textContent = "New Text";
<svg height="30" width="800">
<g inkscape:groupmode="layer" id="layer9" inkscape:label="score" style="display:inline">
     <text xml:space="preserve" style="font-style:normal;font-weight:normal;font-size:22.5px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" x="100.3568906" y="20.353357" id="text5833" sodipodi:linespacing="125%"><tspan sodipodi:role="line" id="tspan5834" x="300.3568906" y="20.353357">Hello</tspan></text>

  </g>
</svg>

Answer №3

Here is a simple example demonstrating how to update text content using both vanilla JavaScript and jQuery:

changeContent("textEl", "New text");
//changeContentWithJQuery("textEl", "Using jQuery now"); // uncomment this line to see jQuery in action

function changeContent(elementId, newText) {
  var element = document.getElementById(elementId);
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }
  element.appendChild(document.createTextNode(newText));
}

function changeContentWithJQuery(elementId, newText) {
  $("#" + elementId).text(newText);
}

You can view the code in action on jsFiddle: https://jsfiddle.net/8hcw4j9u/2/

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

Changing links dynamically through jQuery

Below is the dynamicpage.js script: $(function() { var newHash = "", $mainContent = $("#main-content"), $pageWrap = $("#page-wrap"), baseHeight = 0, $el; $pageWrap.height($pageWrap.height()); ba ...

Is there a way to generate a button that displays the subsequent 5 outcomes from the database without navigating away from the current

I am looking to implement a button on my webpage that, once clicked, will load the next set of five questions from my database. I prefer not to use pagination or the GET method to prevent users from navigating back to previously answered questions. My goa ...

Angularjs ng-class directive: remove a class when a different condition becomes true

The question may not be crystal clear, but I am struggling to come up with a better way to phrase it. My goal is to emphasize a table row using ng-class and conditions. Here's the snippet of code I'm currently working with: <tr ng-class="{sel ...

HTML5's video tags are capable of displaying video content without audio playback functionality

My current project involves importing videos using PHP, utilizing a video tag. However, I've encountered an audio issue while doing so. I've tried various codes such as: <video controls> <source src="https://www.w3schools.com/html/mov_ ...

Getting Permission in the latest Facebook JavaScript SDK: A Step-by-Step Guide

I've been working on transitioning to the new Facebook JavaScript SDK from the old JavaScript library (where I was using Connect) and unfortunately, I'm facing issues with getting the permission dialog to pop up. My goal is to display the permiss ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

When calling a function within a for loop, the function receives the final value instead of iterating through the sequence

I need assistance with setting unique names for objects in an array. I have the following setup: this.array = [{name: null}, {name: null}, {name: null}] Along with a list of reserved names: this.reserved = ["name2", "name3"] My goal is to loop through th ...

Having trouble finding the sum of values in an array using the Reduce method?

I have always used a 'for' loop to calculate sums in tables, but recently I learned about a better way - using the 'reduce' method. Following documentation and examples with simple arrays was easy enough, but now I am working with an ar ...

Guidelines for creating a navigation item using Bootstrap's CSS

Hey there, I have everything working perfectly except for one thing - I can't seem to figure out how to style the text "Profile" to look like the standard Bootstrap nav-item. The "Payments" section is a good reference for what I'm aiming for. ...

I am encountering a problem with the app.patch() function not working properly. Although the get and delete functions are functioning as expected, the patch function seems to be

I am in the process of setting up a server that can handle CRUD operations. The Movie model currently only consists of one property, which is the title. Although I can create new movies, delete existing ones, and even search for a ...

Tips for creating an inline list in MVC

I have a list in MVC that I want to display inline in blocks. List- <ul> <li> @foreach (var item in Model) { <img src="@item.cardFilePath"/> } </li> </ul> CSS attempted here- li { list-style-type: none; displa ...

The password-protected HTML blog remains hidden until the correct entry is entered into the password box, causing

After successfully creating a password redirect page where entering the correct password redirects you to another URL (psswrdtest.tumblr.com with the password as correctpsswrd, redirecting to google.com*), I attempted to improve it by making the password p ...

The header logo disappears when the Vue.js id is added to the body

Currently, I am in the process of transitioning landing page templates from Angular.js to Vue.js version 3. During this process, I have encountered an issue where the script is being applied to the entire body instead of a specific element. The problem ar ...

JavaScript commences in the htaccess file

My website consists of static HTML pages and a JavaScript file that displays an informational message. I am looking for a way to automatically incorporate the .js file into every page on the site without having to manually add it to each individual page. I ...

Having trouble importing Angular flex-layout into my feature module

I'm facing an issue with Angular flex-layout in one of my modules. It works perfectly fine when I import flex-layout in the app module, but only for the app component. However, when I import flex-layout in another module, it doesn't seem to work ...

Error encountered in VUE JS 3: The function vue.initDirectivesForSSR is not recognized as a valid function

I've been encountering some errors while trying to build my Vue web app with this configuration. I have searched for a solution, but couldn't find anyone facing the same issue as me. Any suggestions on how to resolve this problem? The build was s ...

Transforming the header of a table in a CSV file into a schema field

My task is to create a schema for a CSV file using Mongoose, but upon inspecting the file, I discovered it contains nearly a hundred fields or columns. While I am familiar with defining schemas in Mongoose for files with only a few fields, I am unsure ho ...

Unusual behavior observed with Chrome image resizing

I've encountered an odd issue with Chrome related to image resizing when the window size changes. When I have Chrome snapped fullscreen in Windows (double-clicking to snap), and then unsnap the window, the images are not scaling correctly back to the ...

Operate a seamless resizing of container divs within the Bootstrap carousel to avoid any sudden "jump" in size adjustments

In my current project, I am faced with the challenge of smoothly resizing container divs as users switch between image or video assets of varying sizes/heights within a Bootstrap carousel. Currently, the resizing process appears to be abrupt and not visua ...

Performing a file selection in Cypress without the presence of an input element in the DOM

Upon clicking the upload button, a file browser is triggered through the method provided below. To my knowledge, an element is not automatically added to the Document Object Model (DOM) unless explicitly appended to a DOM element. const inputEl = document. ...