user7393973
user7393973

Reputation: 2440

Function to check which element is before the other

How can I create a function that takes 2 elements as arguments and returns the one that is before the other (more up in the HTML code)?

For example, in a document like this:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1 id="title"></h1>
    <h1 id="subtitle"></h1>
    <div>
      <span></span>
    </div>
  </body>
</html>

The function would return:

Pseudocode example:

function firstElement(element1, element2) {
  let elementX = false;
  for ( ... ) {
    if ( ... ) {
      elementX = element1;
    } else {
      elementX = element2;
    }
  }
  return elementX;
}

Upvotes: 1

Views: 147

Answers (1)

Keith
Keith

Reputation: 24181

You could get all Dom elements, place in an array an check the IndexOf..

eg..

Note: I've placed the all array part outside the function in case you were requesting lots of DOM checking, for one offs it could be placed inside.

const first = document.querySelector("[data-pos=first]");
const second = document.querySelector("[data-pos=second]");

const all = Array.from(document.querySelectorAll("*"));

function firstElement(element1, element2) {
  return all.indexOf(element1) < all.indexOf(element2) ?
    element1 : element2;
}


const found = firstElement(second, first);

found.style.backgroundColor = "yellow";
<div>test 1</div>
<div>test 2</div>
<div>test 3</div>
<div>test 4</div>
<div data-pos="first">test 5</div>
<div>test 6</div>
<div>test 7</div>
<div>test 8</div>
<div>test 9</div>
<div data-pos="second">test 10</div>
<div>test 11</div>
<div>test 12</div>

Upvotes: 3

Related Questions