What is the method for extracting text from li elements within an ol element using Nightwatch.js?

I need to create a testing tool using Nightwatch to extract titles from a simple list of items and store them in an array. For example, I want the array to contain: Coffee, Tea, Milk.

<ol>
 <li>Coffee</li>
 <li>Tea</li>
 <li>Milk</li>
</ol>

Thank you for your help in advance.

EDIT>>

Thanks to @SoftwareEngineer171, I was able to use .execute() to inject JavaScript into Nightwatch and now it is functioning correctly. The following code retrieves the number of li items within an ol list (using CSS selector) with the help of @SoftwareEngineer171's code:

module.exports = {
'Demo' : function (client) {
client
  .url('http://mylink.com/items')
  .waitForElementVisible('body', 1000)
  .execute(function(){
    var arr = (function(a, b){
        return (Array(a.length) + '').split(',').map(function(c, d){
            return a[d].innerHTML;
      });
      })(document.getElementsByClassName("listing-view")[0].getElementsByClassName("listing-view-item"));
    return arr;  
  }, ['arr'] ,function(result){
      array_h1 = result.value
      console.log(array_h1.length)
  })
  .pause(5000)
  .end();
  }
};

Answer №1

Here is the solution to your issue.

const array = (function(a){
    return (Array(a.length) + '').split(',').map(function(c, d){
        return a[d].innerHTML;
    });
})(document.getElementsByTagName('ol')[0].getElementsByTagName('li'));

UPDATE

If you need clarification on the code provided above, here it is.
Initially, we define an anonymous function that takes one argument (this is the first function in the code). We pass the argument

document.getElementsByTagName('ol')[0].getElementsByTagName('li')
as the variable a, which represents all the <li> elements. Now, a is an object with the constructor of HTMLCollection, so it's not an array. To extract text from this collection, we must convert it to an array. This is why we create a new array and map each element from the HTMLCollection to our new array. The second function simply copies each element from the HTMLCollection object to the array and then returns the array, as requested.
If you still find terms like constructor, anonymous function, array mapping confusing, I recommend reading through this article for more insights.

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

Guide to scheduling a nodejs cron job to execute every 30 days

I need to set up a cron job using the library cron that will execute every 30 days. ...

jQuery MaskMoney - position input at the start of the field

Check out this jsfiddle I created to showcase the issue I'm facing. Whenever I click on the input field, the cursor automatically goes to the end. This means that I have to start typing cents before dollars, which is not the behavior I want. My desire ...

Tips for locating two values within an array in a Meteor document

In my MongoDB collection, I have documents that contain an object called alltags, which is an array of strings. I know how to search for a specific string within these arrays using collection.find({alltags:"searchstring"}), but I'm unsure of how to se ...

The package.json could not be parsed due to an error

I am currently facing an issue while trying to deploy a JavaScript Node.js project on Heroku. Everything works fine on localhost, but upon uploading, I encounter an "unable to parse" error at : ... "engines" : { "node" : ">0.11.9" }, ... The Error Mes ...

What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS ...

Troubleshooting: The issue with applying 'style' in react-draft-wysiwyg

Is there a way to style my textboxes within a rectangle with a default height? I attempted to use the style attribute in my <Editor /> but it didn't work. import { Editor } from "react-draft-wysiwyg"; import { EditorState } from " ...

What are some strategies for blocking URL access to a controller's method in Rails 3?

My goal is to enhance my Rails 3 application by integrating Javascript/jQuery code that retrieves data from the server and updates the page based on the fetched information. I am considering implementing jQuery's $.get() method for this purpose: $.g ...

Guide on transferring binary image data to a JavaScript function

I have $comment->image_data as the binary data of the image and I want to pass this data to the imgclick() function. Attempting the method below, but encountering an unexpected token error. <img src="data:image/jpg;base64,'.$comment->image_t ...

Tips for Creating and Verifying JWE in Node.js

I attempted to use the following code in order to create an RSA-OAEP and A128GCM JWE generator and validator. It successfully encrypts claims and generates the JWE, then decrypts it and provides me with the original claims when running on node.js. However, ...

Retrieving the innerHTML or innerText of a structural DOM element generated by *ngFor in Selenium

Having trouble accessing the innerHTML/innerText of a structural DOM element, only getting a commented element instead of the child elements. <div class="snap-box"> <label class="snap-heading">Recommendations</label> <div class="r ...

What is the best way to hide a div when an image is positioned on top of it?

Previously, I inquired about creating a "cursor mirror" where the movement of the cursor in the top section of a website would be mirrored in the opposite direction in the bottom section. You can find the original question here. Expanding on that concept, ...

Utilizing MongoDB query for geoLocation with maxDistance parameter

Customer location: customerCoordinates: [83,24] stores: { id:1, location: {coordinates:[85,44]...} maxRadiusDelivery: 2000 //meters }, { id:2, location: {coordinates:[82,34]...} maxRadiusDelivery: 100 //meters } Query: db.wh.find({ 'locati ...

Enhance Bootstrap modals by automatically adjusting the background shadow mask when resizing or changing the content within the modal window

Incorporated within my bootstrap modal window is a form alongside a link that triggers the jQuery functionality of .slideToggle(). By interacting with this link, a concealed div expands. Consequently, the size of the modal popover becomes fluid. Upon click ...

Choose the AuthGuard category in real-time

My application intends to employ two distinct authentication strategies - one for users accessing via a browser and another for the public API. A specific header will be set for browser users, allowing my app to determine the appropriate auth strategy base ...

Is it possible for a chrome extension to allow only specific third-party cookies and storage to be

My Chrome extension inserts an iframe from foo.com into bar.com, creating a situation where bar.com now includes a foo.com iframe. However, I have observed that this iframe encounters difficulties when attempting to write to localStorage if the user has ...

Determine the starting position of a div's CSS bottom using jQuery before the hover animation begins

Currently, I am in search of the CSS value 'bottom' for each div that belongs to the 'shelf-info-text' class. These particular divs can be found inside a parent div called 'shelf-item'. The bottom value is determined automati ...

What is the best way to display JSON responses from AJAX in separate divs with identical class names?

I've been going through a whirlwind of confusion lately, unable to find a solution after spending over 100 hours on this. I'm reaching out for help in hopes that someone can guide me in the right direction! UPDATE: To clarify my issue and seek a ...

I would like to take the first two letters of the first and last name from the text box and display them somewhere on the page

Can anyone help me with creating a code that will display the first two letters of a person's first name followed by their last name in a text box? For example, if someone enters "Salman Shaikh," it should appear somewhere on my page as "SASH." I woul ...

Is there a way to locate and refine the blogs associated with a specific user?

Check out the following blog entries stored in the Database: [ { _id: 5fec92292bbb2c32acc0093c, title: 'Boxing ring', author: 'T. Wally', content: 'boxing stuff', likes: 0, user: { _id: 5fd90181 ...

How to Utilize useRef in React Hooks Without Direct Access to HTML Elements?

When working with React, I find myself in a situation where the HTML elements are being loaded from a separate repository that I monitor using pageLoaded. The updateHeader function contains more code for selecting HTML elements and manipulating attributes/ ...