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

Event emitters from Angular 4 are failing to receive emitted events after the page is refreshed

Hey there, I'm facing an unusual issue with event emitters not functioning correctly during page refreshes. Here's the scenario: First, the user lands on the login page. Upon successful login, they are directed to the home page where I need spec ...

What is the best way to send a prop from a parent component to its child using context in React?

Currently, I am working on fetching data in a React application. My goal is to extract an individual value from the response and pass it as a prop in a context from a parent component. The `trendingData` variable holds information retrieved from an API cal ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

Event listeners can only be removed within the useEffect hook

I have encountered an issue when trying to remove an event listener added inside the useEffect hook. The listener is set up to run once after the first rerender, thanks to the empty array passed as the second argument in the useEffect call. I attempted t ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

How can I stop and hover over time in AngularJs Interval?

Within my UI, I have a time element that is continuously updated using AngularJS Interval. Even the milliseconds are constantly running. Is it possible to implement a feature where the time pauses when hovering over it? Any assistance would be greatly appr ...

Precise object mapping with Redux and Typescript

In my redux slice, I have defined a MyState interface with the following structure: interface MyState { key1: string, key2: boolean, key3: number, } There is an action named set which has this implementation: set: (state: MyState, action: PayloadAct ...

Encountering the error message "This expression cannot be invoked" within a Typescript React Application

I'm working on separating the logic from the layout component in my Typescript React Application, but I suspect there's an issue with the return type of my controller function. I attempted to define a type to specify the return type, but TypeScr ...

Creating a JavaScript class definition without the need for instantiation

I am looking to create an empty data class in JavaScript that can later be filled with JSON data. In C#, I would typically do something like this: class Person { string name; int age; Person[] children; var whatever; } However, when I try ...

axios interceptor - delay the request until the cookie API call is completed, and proceed only after that

Struggling to make axios wait for an additional call in the interceptor to finish. Using NuxtJS as a frontend SPA with Laravel 8 API. After trying various approaches for about 4 days, none seem to be effective. TARGET Require axios REQUEST interceptor t ...

Is it possible to utilize a variable from a Higher Order Function within a different generation function?

I am facing a dilemma with the need to utilize email = user.email in newcomment['comments/'+id] = {id,comment,email,date}. However, I am unable to incorporate email = yield user.email or yield auth.onAuthStateChanged(user => {email = user.em ...

Is there a way to obtain the coordinates of an SVG element by simply clicking on a specific point?

I'm still learning about SVG and I'm trying to trigger an event that captures the click coordinates when clicking on the SVG. I have a few questions: Since I'm using Angular, I'm unsure if it's possible to keep my function in th ...

What is the best way to create a button that will trigger a modal window to display a message?

I am looking to create a button that will open a modal window displaying a message. However, when I tried to add a label and viewed the page, the desired window appeared on top of the rest of the content. But unfortunately, clicking the button did not prod ...

If the number exceeds 1, then proceed with this action

I currently have a variable called countTicked, which holds an integer representing the number of relatedBoxes present on the page. I am in need of an if statement that will perform certain actions when the value stored in countTicked exceeds 1. if (!$(c ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

Update the section tag upon submission using jQuery on a jQuery Mobile HTML page

I have integrated a jquerymobile template into Dreamweaver 6.0 to create a mobile app interface. The home screen features four buttons - specifically, View, Create, Update, Delete. Upon clicking the Create button, a new screen is opened (each screen corres ...

Issue encountered: Unable to access the property 'loadChildren' as it is undefined, while attempting to configure the path

How can I conditionally load the route path? I've attempted the code below, but it's throwing an error. Can someone guide me on how to accomplish this task? [ng] ERROR in Cannot read property 'loadChildren' of undefined [ng] i 「w ...

Is there a way to determine the height of the ion-footer?

Is there a way to obtain the height of the ion-footer element in Ionic2? I want to calculate the initial window height minus the ion-footer height, but I am currently only able to get the overall window height. I'm not interested in retrieving the ...

Adding a .PHP File to Two Separate DIVs

I am using wordpress to create a custom theme. I'm interested in placing all the content from my slider.php file inside a div box on my index.php page. How would I go about doing this? SLIDER.PHP <div class="slider"> // All the image tags wit ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...