Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag.

For example, you can use the following code snippet:

[...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue?.match("something")))

Alternatively, you can refer to another solution provided in this post.

How do I select this text element based on its content?

<body>
  <svg>
    <g>
      <text>something</text>
    </g>
  </svg>
</body>

Answer №1

Utilizing the

[...document.querySelectorAll("*")]
technique involves extracting the nodeValue from each and every element.
This process places the burden on the (slower) JavaScript Engine to handle.

Alternatively, you can leverage the TreeWalker API to specifically target TextNodes.
Here, the responsibility shifts to the (faster) Browser Engine.

IE9 was the final browser to integrate the TreeWalker API, making this approach available for over a decade now...
(despite this, some individuals still opt for the more sluggish jQuery contains or similar methods)

TreeWalker API

  • #Text Nodes possess nodeType 4
    and keep in mind that whitespace characters (space, return, tab) separating nodes are considered TextNodes

  • Note that nodeNames within the HTML NameSpace are UPPERCASE;
    while those within SVG NameSpace are lowercase

<body>
  <svg something>
    <g id=somethingelse>
      <text id=ONE>something</text>
      <text id=TWO>nothing</text>
    </g>
  </svg>
</body>
<script>
  function findNodes(
    str = '', 
    root = document.body
  ) {
    let tree = document.createTreeWalker(root, 4);
    let nodes = [];
    let node;
    while (node = tree.nextNode()) {
      if (node.parentNode.nodeName === "text" 
          && 
          node.data.includes(str)) {
        nodes.push(node);
      }
    }
    console.log('Find:', str)
    nodes.map((text, idx, arr) => {
      console.log(`${idx+1}/${arr.length} `, text.data, ' in:', text.parentNode.id);
    });
    return nodes;
  }
  findNodes('something');
  findNodes('thing');
</script>

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

Creating a typewriter effect with Vue Js

Hey there, I'm having some trouble with the code below while working on my Vue project. It seems to be functioning correctly, but for some reason it's not working in my Vue environment. const text = document.getElementById("text"); const phrase ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

Leverage the power of Angular.JS and ng-table to effectively summarize values in your

I received the following JSON data: var scholars = [{"FirstName":"John","LastName":"Doe","Unit":"PA","Institution":"University of Haifa","teken":1,"FirstYearActive":"2007","hIndex":"3","j2014":0,"j2013":4,"j2012":3,"j2011":0,"j2010":0,"j20052009":2,"j2 ...

What is the best way to process the bytes from xhr.responseText?

Is there a way to successfully download a large 400+ mb Json file using xmlhttprequest without encountering the dreaded Ah Snap message in Chrome due to its immense size? One potential solution I've considered is implementing setInterval() to read th ...

Sending JSON Data from C# to External JavaScript File without Using a Web Server

Trying to transfer JSON data from a C# (winforms) application to a static HTML/JavaScript file for canvas drawing without the need for a web server. Keeping the HTML file unhosted is preferred. Without involving a server, passing data through 'get&ap ...

The error "Prop does not exist on type 'PropsWithChildren'" occurs when attempting to dispatch an action with react-redux

When attempting to dispatch the action, I am encountering this error: The error message reads: Property 'fetch_feed_loc' does not exist on type 'PropsWithChildren<{ onSubmitForm: any; }>'. Another error states: Property &apos ...

Working with TypeScript: Overriding a Parent Constructor

I am new to TypeScript and currently learning about Classes. I have a question regarding extending parent classes: When we use the extends keyword to inherit from a parent class, we are required to call the super() method in the child class constructor. H ...

The columnFilter plugin in Datatables is failing to initialize

I have a pre-existing table that needs to be customized and initialized properly. <table id="currencies-table" class="table table-striped table-bordered table-hover form-data-table"> <thead> <tr> <th style="width: 10px;" ...

Discovering the file names of JavaScript files within a context path and dynamically loading them

I am currently working on a Struts application where I need to dynamically load a JSP file with its corresponding JavaScript file upon menu selection. Although the functionality is working smoothly, I am facing an issue in loading the JavaScript file along ...

Limiting the size of images within a specific section using CSS

When using CSS, I know how to resize images with the code snippets below: img {width:100%; height: auto; } img {max-width: 600px} While this method works effectively, it applies to every image on the page. What I really need is for some images to be ...

`Error encountered when attempting to convert date with Angular JS filter`

Utilizing angular js filter in the controller for date formatting. A user selects a date from a uib-datepicker-popup. The goal is to format this date using ISO 8601 (yyyy-mm-dd) date format. Upon logging the user-selected date, the output is as follows: S ...

Error message: Encountered JavaScript heap out-of-memory error during Azure DevOps React Container Production Build

I am facing challenges in building a React production Docker container with Azure DevOps pipelines. Despite upgrading my build environment and code, the pipeline failed to run successfully. After conducting some research, I attempted to add the "--node-fla ...

Having trouble getting the ValidatorPipe to function properly in my nest.js application

Issue Description There is an issue with the current behavior where initializing a validation pipe for a request body does not reject invalid types as expected. Desired Outcome The expected behavior should be that when a user provides a value that does n ...

How to store angular 2 table information generated using ngFor

I am currently working on a project where I need to create an editable table using data retrieved from the back end. My goal now is to save any updated data. I attempted to use formControl, but it seems to only save the data in the last column. Below is a ...

Creating dynamic form fields in Flask WTForm based on user's previous selection is a useful feature that can be achieved with some

I am interested in developing a form that dynamically generates different text area fields based on the selection made in a dropdown menu beforehand. Specifically, the idea is to create projects of various categories where, for instance, if a user chooses ...

Tips for crafting interactive Dropdown menus

Visit this link for more information Hello all, I am a beginner in HTML and Javascript and seeking guidance on how to create dynamic dropdown menus similar to the ones on the provided website. I have successfully implemented the source code, but my questi ...

The accuracy of the fromPointToLatLng function in Google Map's JS API seems to be inconsistent with the actual events

My objective is to enhance user experience with a drawing tool on the map interface. I aim for a functionality where, upon single-clicking somewhere on the map using tools like the rectangle tool, the map automatically centers on that clicked location. Thi ...

Navigating the issue of "Experiencing additional hooks rendered compared to the previous render"

I'm currently in the process of developing a small application where certain elements will be nested within one another. My approach involves segmenting each component into its own file (children), returning a function with two components in each Rend ...

Troubleshooting: Bootstrap 5 Alert not Displaying on Website

I'm experiencing an issue trying to display a bootstrap alert in my HTML code. Here is the code I'm using: <div class="alert alert-success alert-dismissible fade show" role="alert"> text & ...

How should event listeners be unbound and child elements removed in single page applications?

I've recently delved into the world of memory leaks in JavaScript while working on a large single-page application. After using Chrome's Profiles (Snapshot) function, I noticed an abundance of detached DOM elements indicating a possible memory le ...