Languages
[Edit]
EN

JavaScript / XPath - get preceding sibling element

9 points
Created by:
Iona
415

In this short article we would like to show how to find using XPath, preceding sibling element reference in JavaScript.

In below example we are looking for preceding slibling (/preceding-sibling::input) that occurs as previous of any label element and contains Visible text inside (//label[text()='Visible']).

Quic solution:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="element">
    <label>
      <input type="checkbox" checked />
      <span>Visible</span>
    </label>
  </div>
  <script>
    
    var element = document.querySelector('#element');

    var result = document.evaluate("//span[text()='Visible']/preceding-sibling::input", element);
    var checkbox = result.iterateNext();

    if (checkbox) {
      console.log(checkbox.checked);
    }
    
  </script>
</body>
</html>

 

Alternative titles

  1. JavaScript / XPath - get previous sibling element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript / XPath

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join