-1

Trying to find right xpath selector. Element has only href unique. Is that possible to find element by href="#">iphone X text and parent class class="card h-100". But click <button class="btn btn-info"> which is another child of 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>
Ihor Harmatii
  • 189
  • 3
  • 21

4 Answers4

1

Try the below code using querySelectorAll()

(function() {

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

  console.log(result);
})();
<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>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
1

Here's the XPath that you are looking for with an explanation

//div[@class='card h-100'][.//a[.='iphone X']]//button
^ find a DIV
     ^ with this class
                          ^ that has a child A
                                ^ with text = 'iphone X'
                                              ^ once you find that DIV, find the child BUTTON
JeffC
  • 22,180
  • 5
  • 32
  • 55
1

If I understand correctly, you want to click on the button in the next child class corresponding to 'a' that has text 'iphone X'. For doing so, you can use the following xpath:

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

Hope it helps :)

PRERNA PAL
  • 381
  • 2
  • 10
  • using this method it finds all elements on the page that have `class='btn btn-info'` – Ihor Harmatii Jul 16 '19 at 22:49
  • @IhorHarmatii Please use xpath `//a[text()='iphone X']//ancestor::div[@class='card h-100']//button[@class='btn btn-info']`. With this it will only look for button under div with class as `card h-100`. – PRERNA PAL Jul 17 '19 at 04:48
1

To find the element <button class="btn btn-info"> associated with the text iphone X which have a parent node with class="card h-100" you can use the following Locator Strategy:

  • xpath:

    //div[@class='card h-100']//a[text()='iphone X']//following::button[@class='btn btn-info']
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352