Discovering multiple elements using CSS selectors in Protractor for AngularJS is an essential

Delving into the world of CSS as a newcomer, I aim to steer clear of using xpath in my Protractor AngularJS test automations. Despite successfully targeting a specific element within a list, Protractor warns me about multiple elements found for the locator. To avoid such issues in the future, especially when not always needing the first list item, I seek clarity on leveraging CSS to reach my destination - a task made challenging by vague documentation. My current focus is on capturing the "Marketing Venue" element but will eventually expand to include other elements below it. The snippet showcases how AngularJS currently aids in retrieving text data. Much appreciated for any insights.

var iPlanLevel=element(by.css("div:nth-of-type(2) > div:nth-of-type(2) > div > div:nth-of-type(1) > span")).getText().then(function (text) {
  console.log(text);
}
);

<!-- begin snippet: js hide: false -->
<div class="home-info">

  <span class="web-developer-id-class-details"></span>
  <div class="home-top home-section"></div>
  <span class="web-developer-id-class-details"></span>
  <div class="home-bottom home-section">
    <h3></h3>
    <span class="web-developer-id-class-details"></span>
    <div class="home-box">
      <span class="web-developer-id-class-details"></span>
      <span class="home-name"></span>
      <br></br>


      Lindemannstrasse 88

      <br></br>


      Dortmund 44137

      <br></br>
      <br></br>
      <span class="web-developer-id-class-details"></span>
      <div class="property-group meduim">
        <div></div>
        <span>

                    MarketingVenue

                </span>
      </div>
      <span class="web-developer-id-class-details">

                .property-group.meduim

            </span>
      <div class="property-group meduim">
        <div></div>
        <span>

                    December 31, 2016

                </span>
      </div>
      <span class="web-developer-id-class-details"></span>
      <div class="property-group meduim"></div>
      <div></div>
      <br></br>
    </div>
    <span class="web-developer-id-class-details"></span>
    <div class="home-box"></div>
  </div>

</div>

Answer №1

Have the capability to alter the HTML being tested? If so, consider adding a tag within the Marketing Venue span for enhanced utility. For example, you could insert name="marketingVenue", allowing you to implement something similar to this:

// Utilizing shorthand for element selection by css selector ($ = by.css())
var marketingVenue = $('[name="marketingVenue"]');

// Employing css selector shorthand for child selection
var marketingChild = marketingVenue.$('[name="childBeneathMarketingVenue]');

// Selecting a child using a variable and element(el.locator())
var marketingChildSelector = $('[name="childBeneathMarketingVenue"]');
var marketingChild = marketingVenue.element(marketingChildSelector.locator());

If modifying the HTML is not an option, the code above can still be utilized with a longer, albeit fragile css selector.

To address warnings related to multiple elements, all elements must be obtained, then either .first or .get(x) used to select a specific one from the array.

// Obtain all elements with a specified tag using shorthand $$ element.all(by.css(x))
var marketingVenues = $$('[name="marketingVenues"]');
var firstMarketingVenue = marketingVenues.first();
var specificMarketingVenue = marketingVenues.get(12); // Retrieve the 13th element from the array

This function can also be employed to exclusively retrieve visible element(s), assuming that the html contains both hidden and visible elements.


// Input a string css selector to fetch the initial visible element of that selector
function getVisibleElements(selector){
    var allElementsOfSelector = element.all(by.css(selector));
    var displayedElement = allElementsOfSelector.filter(function(elem) {
        return elem.isDisplayed('cannot find' + ' ' + selector);
    }) // Add '.first();' at this point if only the first visible element is desired
    return displayedElement;
}

var visibleMarketingVenues = getVisibleElements('[name="marketingVenues"]');
var marketingVenue = visibleMarketingVenues.first();
var fifthMarketingVenue = visibleMarketingVenues.get(4);

In cases where modification of the html is not feasible, altering the selector may be necessary if any changes occur on the page itself, as div selectors are notably delicate. Your current selector may resemble the following:

var marketingVenue = $$('.property-group').get(0).$('span');

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

Update the date format in the user interface datepicker for jHipster

Recently, I created a project using Spring Boot and Angular 1 in jHipster. As someone who is new to Angular, I encountered an issue with the date format when using the UI datepicker from https://angular-ui.github.io/bootstrap. Despite setting Spanish as th ...

I'm trying to figure out how to retrieve data from a JQuery autocomplete response that contains an array. Specifically, I want

https://i.stack.imgur.com/YpuJl.pngThis form field is for entering text input. <span> <img src="images/author2.jpg" width="50" /> //The profile picture displayed here is static but in the database I have a dynamic image. <input class="sea ...

Bootstrap carousel slide animation isn't transitioning properly

I am encountering an issue with my carousel animation. I am aiming for a slide-out/slide-in effect similar to the Bootstrap website, but instead of sliding out, the old item simply disappears and the new item slides in. I have included a GIF to illustrat ...

Dynamic addition of modules to my Angular application is a must

Is there a way to dynamically load modules in my Angular application based on user selection after they have logged in? ...

Discovering the Javascript Code Executing on a <span> element with the Help of Chrome Inspector or Firebug

I have encountered a situation where a website is dynamically generating information into <span></span> tags using jQuery. The span has a class of "Price" and an id corresponding to a Product Code, with the data being pulled from a JSON data sh ...

The :before pseudo element doesn't seem to be functioning properly on Internet Explorer 11

The following code works well in Chrome and Mozilla, but unfortunately does not function correctly in IE11. I am attempting to apply a background color on hover to a div with the class .border-green, however this functionality is failing specifically in ...

Uniform Fixed Width for Material UI Table Cells

Below is a Material UI Table with columns set to a fixed size of 205px each, and the table itself set to 100% width. However, when there isn't enough space available, the columns do not shrink according to the text inside them, remaining stuck at 205p ...

Trigger event once item is selected from the jQuery combobox dropdown

I have implemented a custom autocomplete combobox using the jQuery UI library to create text fields with dropdown functionality. This hybrid input allows users to either select an item from the dropdown or enter free text manually. However, I need to trigg ...

Exploring the World of AngularJS HTTP Interceptors

Do HTTP Interceptors in AngularJS affect performance? I am interested in intercepting requests and adding the absolute URL: angular.module('app').config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push( ...

Angular application defaulting to Hashbang element

Are the latest versions of angular/angular-route 1.6.1 set to use hashbang by default? It's interesting because, in this code snippet, I found that I have to use #! when linking to partials as #/ or #/partial2 doesn't seem to work. I was under th ...

serving static files with Express.js and integrating an Angular application

I want to load a Yeoman Angular app only when a user accesses a specific page in Express (like '/dashboard'). The idea is to have multiple static front pages on Express without using Angular, and then switch to the Angular routes/application onc ...

How to create a custom input border style while maintaining the focus outline in Firefox and Internet Explorer

Note: I am not looking to remove or customize focus styles for accessibility purposes. It is extremely difficult to replicate all the various focus styles across different browsers and operating systems. When customizing the appearance of an input/textare ...

The click event in AngularJS is functioning properly, while the load event is not functioning correctly

As a newcomer to angularjs, I am attempting to run a function once a div has finished loading. app.js var app = angular.module('myApp',[]); app.directive('orientable', function () { return { link: function(scope, e ...

What is the best way to align a table (datatable) to the left?

How can I align the table to the left without using float:left in the following code? Applying text-align: left to the parent element of the table doesn't seem to work as expected. http://jsfiddle.net/william/B4qJG/1 HTML: <div class="valueList" ...

"Help needed: The HTML dialog element is obstructing the invisible reCAPTCHA challenge popup. Any solutions for resolving this

Visit this link to access the example in incognito mode. Click on the "open" button to open the sample signin form, then click on the "Sign Up" button to trigger the challenge. There seems to be an issue with using recaptcha inside a dialog. I'm not ...

Angular <select><option> tags are missing from the browser display, although they are present in the source HTML code

After incorporating a dropdown list into the FormGroup, it seems to be missing from the browser display. Upon inspecting the page's HTML source on Chrome, I noticed that the <select><option></option></select> element is present ...

Arrange the elements within the anchor tag in a vertical line using Angular Material

Is there a way to style the elements within an anchor tag in Angular Material so that they display in a single line? I am looking for the CSS solution to achieve this outcome. This is my current HTML code: <a mat-list-item [routerLink]="['das ...

issue in Angular.js with ng-if not rendering correctly

I have a directive that I want to render when the search results are returned. My approach is to start with a scope variable algoliaSearch set to false, and then change it to true once the search results are received. In my view, I attempt to render the di ...

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

Layout of CSS grid being created dynamically

The concept of the CSS grid layout, as explained here, demonstrates that the grid cells are structured in the markup without hierarchy. The arrangement into rows and columns is managed through CSS directives like grid-template-columns. An illustration for ...