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

    AngularJS xeditable: sending updated data to the server

    I am currently utilizing AngularJS to display products in a table for my users. Users have the ability to filter the table using categories or keywords. However, they should also be able to edit the product information within the table, such as product nam ...

    Learning to retrieve specific properties from an event target in JavaScript

    Here is the code snippet I am working with: <h1 msgId = "someId"> Some text </h1> And in my code.js file, I have the following function: document.addEventListener('click', function(e) { target = e.target; }, false); I am tryin ...

    Crafting personalized objects from an array

    In the process of creating an object from an array, I am faced with a dilemma. The elements in the array are as follows: var arr = [ 'find({ qty: { $lt: 20 } } )', 'limit(5)', 'skip(0)' ] Despite my efforts, my code is ...

    One potential solution is sending a message to a user via a server using JavaScript on Node.js

    Hey there, I've encountered a minor issue and would appreciate your help. Recently, I developed a weather program in NodeJs where users can search for the weather in their city. However, I'm facing a challenge with displaying the weather data to ...

    "Exploring the Depths: How Node.js Utilizes Recursive Calls

    I need assistance generating a comprehensive list of all users' flairs on a specific subreddit. To achieve this, Reddit breaks down the requests into chunks of 1,000 and offers both "before" and "after" parameters for fetching purposes. However, I am ...

    Encountering issues with Monaco Editor's autocomplete functionality in React

    I'm facing an issue with implementing autocomplete in the Monaco Editor using a file called tf.d.ts that contains all the definitions in TypeScript. Despite several attempts, the autocomplete feature is not working as expected. import React, { useRef, ...

    Implementing dynamic width with ng-style in AngularJS

    I am trying to dynamically resize a div when an event is fired from S3. In the code below, I pass the progress variable to the updateProgress function as a parameter. This function resides in the top scope of my Angular controller. s3.upload(params).on(& ...

    React.js: Dynamically Highlighting Menu Items Based on Scrolling位置-GaidoWhen a

    Having trouble finding a solution for this issue. I'm currently working on creating a navigation bar with scroll-to functionality, where clicking on a menu item scrolls the page to the corresponding section. However, I am unsure how to change the colo ...

    Tips for updating Nodejs' module dependency to a newer version

    Currently, my project utilizes the react-cropper library which includes version cropper ^0.10.0. However, I require certain methods from cropper version 0.11.1. To address this issue, I decided to fork the project to my own GitHub repository in order to up ...

    The alignment of the Slick slider item appears off-center when viewed on a mobile device

    https://i.stack.imgur.com/kwxaX.png When viewing the items on a mobile device, they are not centered as desired. The issue lies with the first item not being displayed in the center. How can this problem be addressed? Here is the code snippet: slickOptio ...

    Limit the usage of map() to solely operate on a collection of headers stored within an array generated from a specified range

    I need to limit the map functionality to only include columns within the specified range that are also present in the headers list, which is a subset of the values in v[0]. This ensures that only values from columns listed in the headers array will be mo ...

    What causes parameters to be initially passed as undefined when sending them from one component to another, only to later arrive with the actual data intact

    When passing properties from a parent component to a child component, my code gets executed before the properties arrive. This results in an error stating "Cannot read properties of undefined (reading 'map')". Why does this occur? https://i.ssta ...

    Incorporating video.js into an Angular website application

    I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...

    Encountering unidentified data leading to the error message "Query data must be defined"

    Currently, I'm utilizing Next.js to develop a project for my portfolio. In order to manage the API, I decided to implement both Tanstack query and Axios. The issue arises when attempting to retrieve the data as an error surfaces. Oddly enough, while ...

    I encountered a difficulty trying to assign a value to @Input decorators in the spec file

    While writing a test case for form submission, I encountered an issue where the Input decorator (e.g. station) value is reassigned during form submission. However, when attempting to define this Input value in the spec file, the component.station value is ...

    Troubleshooting a VueJS Problem: Updating $data in the mounted hook

    Revision This snippet of Component.vue was extracted from a larger web application where I made a mistake that had significant consequences, all because of a small change I didn't initially notice. An important distinction exists between the followi ...

    Why do the async functions appear to be uncovered branches in the Jest/Istanbul coverage report?

    I am encountering an issue throughout my application: When running Jest test coverage script with Istanbul, I am getting a "branch not covered" message specifically on the async function part of my well covered function. What does this message mean and how ...

    What could be causing me to receive 'undefined' and an empty array[] when using Promise.all with JavaScript async operations making calls to Azure APIs?

    In my personal project utilizing Azure AI APIs and Node.js/Express,, I am working on handling a get request to a /viewText route by extracting text and key phrases from an uploaded image/document. Below is the code snippet that should log this data to the ...

    Restricting the drop zone for a jqueryui sortable element

    In my HTML code, I have a list of elements inside a ul tag. The last li element is supposed to create new items. I used jqueryui's sortable() function to make the ul sortable, but excluded the last li element from being draggable. However, other items ...

    Switching measurement unit to jQuery when retrieving image weight

    After coming across a solution on this question, I am looking to determine the weight of an image from a file input. The solution I found displays the result in MiB (Mebibyte) unit. Is there a way to show the image weight using the same code, but in a diff ...