JavaScript / XPath - get preceding sibling element

9 points
Created by:

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>
  <div id="element">
      <input type="checkbox" checked />
    var element = document.querySelector('#element');

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

    if (checkbox) {


Hey ūüĎč
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.