Locate the parent element using a unique child element, then interact with a different child element

Can you help me come up with the correct xpath selector for this specific element? The element only has a unique href. Is it possible to locate the element by searching for the text iphone X within the href="#">iphone X and also checking for its parent class class="card h-100"? Once found, I need to click on the

<button class="btn btn-info">
which is another child of the same parent class.

  <div class="card h-100">
    <div class="card-body">
      <h4 class="card-title">
        <a href="#">iphone X</a>
      </h4>
    </div>
    <div class="card-footer">
     <button class="btn btn-info"></button>
    </div>
  </div>

Answer №1

Discovering the precise XPath you seek, along with a detailed explanation

//div[@class='card h-100'][.//a[.='iphone X']]//button
^ locate a DIV element
     ^ having this specific class attribute
                          ^ that contains an anchor (A) element
                                ^ containing the text 'iphone X'
                                              ^ once you identify that DIV, retrieve the child BUTTON element

Answer №2

Check out this sample code utilizing querySelectorAll()

(function() {

  var links = document.querySelectorAll('a[href="#"]');
  var filteredLinks = [];
  links.forEach(function(link) {
    if (link.innerHTML == 'iphone X' && link.parentElement.parentElement.parentElement.className.includes('card h-100')) {
      filteredLinks.push(link);
    }
  });

  console.log(filteredLinks);
})();
<div class="card h-100">
  <div class="card-body">
    <h4 class="card-title">
      <a href="#">iphone X</a>
    </h4>
  </div>
  <div class="card-footer">
    <button class="btn btn-info"></button>
  </div>
</div>

<div class="card h-100">
  <div class="card-body">
    <h4 class="card-title">
      <a href="#">iphone XS</a>
    </h4>
  </div>
  <div class="card-footer">
    <button class="btn btn-info"></button>
  </div>
</div>

<div class="card h-200">
  <div class="card-body">
    <h4 class="card-title">
      <a href="#">iphone X</a>
    </h4>
  </div>
  <div class="card-footer">
    <button class="btn btn-info"></button>
  </div>
</div>

Answer №3

If my interpretation is accurate, your goal is to select the button within the subsequent child element that matches the text 'iphone X'. To achieve this, you can utilize the xpath provided below:

//a[text()='iphone X']//ancestor::div//button[@class='btn btn-info']

I trust this solution proves useful :)

Answer №4

If you're looking to locate the

<button class="btn btn-info">
element that corresponds to the text iphone X within a parent node with the class card h-100, you can utilize the following Locator Strategy:

  • xpath:

    //div[@class='card h-100']//a[text()='iphone X']//following::button[@class='btn btn-info']
    

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

What is the best way to handle JSON data errors when a value is undefined?

I am currently working on a piece of code that displays JSON data in HTML. However, if a value is undefined, it doesn't display anything. How can I handle this error so that if a value is undefined, it will show "N/A" instead of breaking the code? ...

The AJAX response doesn't seem to be halting

My AJAX request looks like this: $.ajax({ url: "AutoRFQ_Vendors_ST.aspx/BindVesselGrid", type: "POST", timeout: 3000, data: JSON.stringify(sendingdata), ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

What is the most efficient way to use jQuery to retrieve the count of tags associated with a variable

I am trying to filter my data retrieved from ajax using a function. Here is the initial code: var csvf = data.filter(function (el) { return ['TRUCK_CPX'].indexOf(el.TAG) >= 0 && ['CA5533'].indexOf(el.Chave) >= 0 }); Now ...

Troubleshooting AngularJS ng-route and Three.js crashes and glitches: A comprehensive guide

I am currently working on a website that utilizes angularjs along with the ng-route directive for navigation between different views. The site also incorporates Three.js for WebGL rendering on canvas. However, I am encountering difficulties as the applicat ...

Send the Vue component as an argument to the function

Currently, I am in the process of transferring a project to Vue and utilizing Muuri as a layout manager. In my code, I have the following snippet: grid.add(itemElem, { layout: false, active: false }); The variable itemElem used to be an HTML element c ...

Tap on the image to enlarge

I have a question regarding using thumbnails from Bootstrap. I am trying to create functionality where when I click on a thumbnail, the picture with its original sizes appears and then disappears when clicked anywhere else on the page. Below is an exampl ...

I am having an issue with my registration form in node.js where it does not redirect after submitting

I am currently working on implementing a registration form using node/express for my website. The routes are all set up and the database connection is established. However, I am encountering some issues when users try to submit the registration form on th ...

How can I display two different styles on a single page in ASP.NET MVC without any conflicts between CSS classes?

Currently, I am developing a web-based application that is capable of generating documents containing specific data. A new functionality has been introduced in the document generator, allowing users to input an Atlassian Confluence link into a designated t ...

Dealing with two form submissions using a single handleSubmit function in react-hook-form

I have a React app with two address forms on one page. Each form has its own save address function that stores the address in the database. There is a single submit button that submits both fields and redirects to the next page (The plus button in the circ ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

Generating a unique JavaScript array by extracting data from an HTML input element

I am working on a basic HTML form that requests a number between 1 and 10 from the user. Depending on this number, I aim to generate a new array. Currently, the code displays an alert box with the newly created array, but my end goal is to have a table p ...

The ajax keypress event is malfunctioning and the ActionResult parameter is failing to capture any data

I am facing an issue where I want to update the value of a textbox using AJAX on keypress event, but the controller is not receiving any value to perform the calculation (it's receiving null). <script> $('#TotDiscnt').keypress(fu ...

Looking for a way to add a permanent footer to the bottom of your webpage without affecting the tab order for accessibility?

I have a paginated form with a fixed navigation footer at the bottom that needs to stay in place even when scrolling. This footer should also be at the bottom of the page for mobile devices and tablets. To achieve this, I used position: fixed on the foote ...

How to center elements using Bootstrap 4 and flexbox styling

Just starting out in web development. I currently have the following HTML: <section class="boxes"> <div class="container-fluid"> <div class="row"> <div class="col-12 col-lg-4 box1&q ...

How can you achieve a vertical list display for a label while preserving its inline-block properties?

I have chosen to use labels for my radio buttons because I enjoy the convenience of being able to click on the text to select the option. However, I want these labels to appear in a vertical list format. Currently, they are displaying as blocks, causing th ...

What is the best way to retrieve the value of the nearest text input using JavaScript?

I am currently working on designing an HTML table that includes a time picker in one column for the start time and another time picker in a separate column for the end time within the same row. My goal is to retrieve both values (start time and end time), ...

Capture the onclick attribute with jQuery and then reapply it

I am facing a challenge with a page that has several calendars composed of HTML tables where each day is represented by a td. The td elements have an onClick attribute which I need to manipulate using jQuery. Specifically, I need to remove the onClick attr ...

What is the best way to create a seamless Asynchronous loop?

Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List and Item (with a list containing items as well as additional associated data). For ins ...

Anticipated spatial glitch problem involving the gadicc/meteor-reactive-window package for Meteor

Utilizing the gadicc/meteor-reactive-window Meteor Package to switch templates based on screen size. This file is named pictureDisplatSection.html <template name="pictureDisplaySection"> <div class="display"> ...