How to retrieve the name of a node using partial text in JavaScript

I am looking for a way to separate values into key-value pairs before and after a specified delimiter (:) in JavaScript.

For example:

  • Product Name: Product 15
  • Product code: 1234
  • If I search for "product," I want to retrieve the product name and product code as keys, and their respective values (Product 15 and 1234).

    var text1=document.documentElement.innerHTML;
    var res = text1.match(/Product/g);
    
    for(j=0;j<res.length;j++)
    {
       console.log(res[j]);
    }
       <li>Product name: Product 15</li>
       <li>product code: 1200</li>
       <span> product category : bag </span>

    Answer №1

    Retrieving the HTML string from the DOM using

    document.documentElement.innerHTML;
    and searching it can make it challenging to navigate back to the parent node due to lack of a node relation. It is advisable to identify the necessary elements for search and iterate over them for efficient searching.

    Instead of using text1.match to find matching words in the text, opting for regex.test will help determine if the required word or pattern exists. It is important to execute this on individual texts rather than on the complete HTML string to retain information about the parent node.

    var elements = document.querySelectorAll("li,span");
    var regex = /product/i
    
    for (var j = 0; j < elements.length; j++) {
      var text = elements[j].textContent;
      if (regex.test(text)) {
        console.log(text);
      }
    }
    <li>Product name: Product 15</li>
    <li>product code: 1200</li>
    <span> product category : bag </span>

    Answer №2

     var items=[];
     $('li').each(function(e){var e_text = $(e).text().split(':'); items.push({[e_text[0]]:e_text[1]})});
    
    // display results
    console.log(items);
    

    JavaScript

    var options = document.getElementsByTagName('li');
    var items=[];
    Array.from(options).forEach(function(ele){var ele_text = ele.innerText.split(':'); items.push({[ele_text[0]]:ele_text[1]})})
    
    // display results
    console.log(items);
    

    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

    How to retrieve data from a form object sent via cloud function using App Script

    Currently, I am in the process of developing a web application that can extract files from a web form and store them in a designated Google Drive folder. After the user submits the form, my goal is to trigger a cloud function using google.script.run while ...

    The logo image dynamically switches as the user scrolls through various colored sections

    Looking to create a feature that changes the logo image as users scroll through different colored sections. Specifically, switching between dark and light themes. a) How can we determine if the section the user is currently on has a dark or light theme? b ...

    Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

    Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

    Is there a way to create an infinite fade in/out effect for this?

    Is there a way to ensure that the method runs after the "click" event in this code snippet? The code currently fades in and out the div #shape while the start variable is true, but when I call the "start" method from the "click" event, the browser stops wo ...

    When I request the value of a JavaScript object, I am met with 'undefined'

    I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...

    Accessing Struts2 tag attributes with JavaScript

    Currently, I am using struts2 with jsp. Within the JSP file, there is a table with several rows of data. To display the row data in the table, iterators are being used. Each row includes a button that allows the user to update the row's data, such as ...

    I'm having trouble with my .Refine feature when attempting to create a conditional input field. Can anyone help troubleshoot this issue?

    I devised a feature in my form that generates additional input fields if the user selects 'yes'. How can I make these input fields mandatory and display a warning message when 'yes' is selected? const FormSchema = z.object({ type: z.e ...

    React Native: Struggling with Button Styling

    I am relatively new to React Native, although I have experience with React in my professional work. I'm finding that applying styles to components in React Native is a bit different than what I'm used to. Specifically, I am struggling to apply s ...

    I'm facing issues with Angular commands not functioning properly even after installing the Angular CLI and configuring the

    Every time I attempt to create a new project using Angular CLI by typing: ng n app I encounter the following error message: C:\Users\Venkateshwarn M\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng: ...

    I am looking to host several iterations of jQuery on a content delivery network within my Nuxt application

    Currently, we are loading jQuery 3.1.4 externally from a CDN on the top page. index.vue head: { bodyAttrs: { id: 'overview' }, script: [ { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min ...

    Eliminable Chips feature in the Material UI Multiple Select component

    The Material UI documentation showcases a multiple select example where the selected options are displayed using the Chip component and the renderValue prop on the Select. By default, clicking on the current value opens the list of available options. I am ...

    Connecting a href link to a TAB

    Check out this useful CODE example I am using. I have a webpage with links that have href attributes. Now, I want to link these pages to another page and have them automatically open a specific tab when clicked. Is this possible? Here are the links on th ...

    Updating a value in Expressjs variable is not working as expected

    In the code snippet below, I have declared a variable called sumOfRevenue. I assigned it a value of 10 in the router, but when I try to print its value, it comes out blank. Can you please help me understand why it's not showing as 10? Please review t ...

    Building a Dynamic Web Widget with the Perfect Blend of HTML, JS,

    While developing a javascript-based web widget, I am aiming to steer clear of using iframes and avoid relying on the page's CSS. It is infeasible for me to utilize custom CSS, as it defeats the purpose, and iframe integration would not present a user- ...

    Using Node.js to create a RESTful API that pulls information from MongoDB

    I am currently working on creating a REST API using Node.js to retrieve the last N rows from a MongoDB collection. Here is my current code snippet: var express = require("express"); var app = express(); var bodyParser = require("body-pa ...

    Downloading a file through a JavaScript link in HTMLUnit: A step-by-step guide

    Looking to download a file with HTMLUnit from a javascript link is proving to be quite challenging. The journey begins at this page. When clicking on the "Authenticate with Java Web Start (new method)" link, a .jnlp file is downloaded, initiating a Java pr ...

    Give a jQuery Mobile flipswitch a new look

    Currently, I am using jQuery Mobile and recently attempted to refresh a flipswitch. However, upon executing the code $("#flipEnabled").slider("refresh");, I encountered an error in the console: Uncaught Error: cannot call methods on slider prior to initial ...

    Identifying when a user closes a tab or browser to trigger a logout in JavaScript with Vue.js using the Quasar framework

    Is there a way to trigger the logout function only when the tab or browser is closed, and not when the page is refreshed? I attempted the following code example, which successfully triggers the logout on tab close but also logs out when the page is ref ...

    Merge a dropdown menu with an alphabetically arranged list that is interactive with clickable options

    I am still learning HTML and Javascript but I'm doing my best. Currently, I am facing a challenge where I need to create a button that, when clicked, opens a dropdown menu containing a table of data. The user should then be able to select a number fr ...

    Creating HTML elements dynamically with attributes based on the `as` prop in React using TypeScript

    Is there a way to dynamically create HTML elements such as b, a, h4, h3, or any element based on the as={""} prop in my function without using if guards? I have seen a similar question that involves styled components, but I am wondering if it can be done ...