Tips for retrieving an element's outerHTML, innerHTML, and text content using JavaScript

I am new to the protractor framework and I have been struggling to find a way to access, using outerHTML/InnerHTML/getText(), the child elements in order to test if an <img> element is being displayed on a view. Specifically, I am working with an ng-grid and trying to locate an img element within its first column while also checking for a specific attribute, such as src=res/someImg.png.

Below is the code snippet that I am currently dealing with:

html

<div>
  <a>
    <div>
        <div>
            <span>
                <i><img src="res/someImg.png"></i>
            </span>
        </div>
        <div>
            ...
        </div>
        <div>
            ...
        </div>
    </div>
  </a>
</div>

test

it('should render an icon in agent list', function () {
    var row = element.all(by.repeater('row in renderedRows')).get(3);
    expect(row).not.toEqual(null); //passes
     expect(row.element(by.css('img')).getAttribute('src').getText()).toMatch(/someImg.png/);//fails with null
    expect(row.element(by.css('span')).outerHTML).toBe('<i><img src="res/someImg.png"></i>'); //fails
    expect(row.element(by.css('i')).innerHTML).toBe('<img src="res/someImg.png">'); //fails

});

If anyone could provide insight into what I might be doing incorrectly, it would be greatly appreciated.

Answer №1

Make sure to apply getAttribute() in all three scenarios: for src, outerHTML, and innerHTML:

verify(row.element(by.css('img')).getAttribute('src')).toMatch(/someImg.png/);
assert(row.element(by.css('span')).getAttribute('outerHTML')).toBe('<i><img src="res/someImg.png"></i>');
check(row.element(by.css('i')).getAttribute('innerHTML')).toBe('<img src="res/someImg.png">');

Confirmed - successful outcome observed.

Answer №2

To be more clear:

verify(row.element(by.css('img')).getAttribute('src')).toIncludeString(/someImg.png/);
verify(row.element(by.css('span')).getFullHtml()).toBe('<i><img src="res/someImg.png"></i>'); 
verify(row.element(by.css('i')).getInnerHtmlContent()).toContain('<img src="res/someImg.png">'); 

Answer №3

According to alecxe's statement dated Aug 24, '16, the methods getOuterHtml() and getInnerHtml() have been deprecated in WebDriverJS and Protractor (refer to )

It is now recommended to use the following code to obtain innerHTML content (as mentioned here: https://github.com/angular/protractor/issues/4041#issuecomment-372022296):

let i = browser.executeScript("return arguments[0].innerHTML;", element(locator)) as Promise<string>;

Here's an example utilizing a helper function:

function getInnerHTML(elem: ElementFinder): Promise<string> {
    return getInnerHTMLCommon(elem, elem.browser_);
}

function getInnerHTMLCommon(elem: WebElement|ElementFinder, webBrowser: ProtractorBrowser): Promise<string> {
    return webBrowser.executeScript("return arguments[0].innerHTML;", elem) as Promise<string>;
}

const html = await getInnerHTML(browser.element(by.xpath("div[1]")));
console.log(html);

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

`The height attribute of the textarea element is not being accurately adjusted`

When I tried to match the width(178px) and height(178px) of my table to the width and height of a text area upon clicking a button, I encountered an issue. While setting the width works perfectly fine, the height is being set to only 17px. It seems like ...

Unable to send post parameters to Yii2 controller using an XHR request

Within the context of my project, I am making an xhr request to a yii2 controller. Here is how the request is structured in my view: var xhr = new XMLHttpRequest(); xhr.open('POST', '$urlToController', true); xhr.setRequestHeader("Co ...

The webpack vue-loader throws an error message stating "unexpected token {" when processing a single-page .vue component

As a C# backend developer, I am venturing into the world of Vue.js. I typically work with Visual Studio 2017 + ASP.NET MVC (using it as an API + one layout) + Vue.js + Webpack. .vue single-page component files are loaded by vue-loader, while .js files a ...

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Stunning Opening and Closing Animation with Ajax

Looking for help with creating an animation like the one shown here: Incorporating this into my current site at: dageniusmarketer.com/DigitalWonderland/ I want the window displaying text content to open and close as users navigate through the links, ess ...

Prevent a sliding panel from responding if there is no input text by incorporating jQuery

I have a straightforward example of user input and a button that reveals "Hello World" when clicked: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

Issue encountered when utilizing a custom service in AngularJS

Recently, I created an angularjs service and tried to access it in a controller by injecting the service into the controller. Below is the code snippet that I implemented: angular.module('ControllerModule').controller('AwarenessCntrl&apos ...

The process of sending parameters to an API in ReactJS: a guide

My objective is to target .....the values originating from login (can be anything)-> for example email:'[email protected]' password:'12345678' I am required to extract the username until "@" and use it as a username i ...

retain focus even after using .blur()

Currently, I am implementing a form submission using AJAX. The form consists of only one input field and the submit button is hidden. My aim is to ensure that when the user hits the enter key, the input field does not lose its focus. Here's the code s ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

A Beginner's Guide to Duplicating Bootstrap Containers in Jade

I am working with JSON data that is being transmitted from an Express and Mongoose Stack to be displayed on the user interface created in Jade. I am wondering which Jade Construct I should use to loop through a Bootstrap Container of col-md-4 using Jade s ...

Encountered a problem during the installation of tensorflowjs for node | Received an error: Command failed: node-pre-gyp install

While attempting to install @tensorflow/tfjs-node, I encountered the following error: Command failed: node-pre-gyp install --fallback-to-build. Is there a solution to resolve this issue? Below is the complete log: npm ERR! code 1 npm ERR! path E:\ ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

Is there a way to schedule a function to run every 6 hours in node.js based on actual time instead of the device's time?

var currentTime = new Date().getHours(); if(currentTime == 6){ //function Do stuff } if(currentTime == 12){ //function Do stuff } if(currentTime == 18){ //function Do stuff } if(currentTime == 24){ //function ...

Troubleshooting: Jquery show effects not functioning as expected

Currently, I am facing an issue where I am attempting to display a fixed div using the show function of jQuery. Although the show function itself is working properly, when I try to include an effect from jQuery UI, it does not seem to work as expected. Bot ...

Executing a npm script (script.js) with custom arguments - a step-by-step guide

I'm considering creating a setup similar to lodash custom builds. Basically, I want to allow users to input a command like: lodash category=collection,function This would create a custom module with the specified category. I've been looking in ...

Unable to execute Protractor using Node.js command line

Hi there! Currently, I am in the process of setting up protractor for the very first time using Node.js. I found detailed instructions on how to do this on the AngularJS website under the section "Running E2E Tests": https://docs.angularjs.org/tutorial Ho ...

An error popped up while using the fetch API due to an unexpected end of input

fetch('http://www.freegamesforyourwebsite.com/feeds/games/?tag=platform&limit=100&format=json', { method:'GET', mode:'no-cors', dataType: 'json', headers: { 'Accept': 'a ...

Require.js and R.js optimizer overlooks shimming configuration

I am facing an issue where R.js is not loading my shim properly, causing jQuery to load before tinyMCE which results in tiny being initialized before it has fully loaded. How can I resolve this problem? build-js.js: var requirejs = require('requirej ...

Utilizing PHP variables to dynamically assign names to radio input tags, and then extracting their values using jQuery or JavaScript

I am facing an issue with my PHP file that generates radio buttons based on unique pets ids. The variable $idperro is constantly changing to distinguish the set of radio buttons. My goal is to insert the value inside the p tag. Here's the PHP code sn ...