Skip to content
Advertisement

Checking the order of children of a div element are in correct order [closed]

I have an object like below

<div class="some class">
  <h3>This is H3 tag</h3>
  <h1>Testing H1 element</h1>
  <p>Hey this is p tag</p>
  <h3>This is H3 tag</h3>
  <h2>I am H2</h2>
  <h3>This is H3 tag</h3>
  <p><b>I am Bold</b></p>
  <h4>I am H4<br></h4>
</div>

Now I want to return true if the above tags inside the div are in the correct order. The correct order should be always
h1->h2->h3->h4. we can have any tag (ex: p, strong) in between.
I got the above object in my javascript file, but not sure how to check if those are in the correct order or not.

Note: There can be multiple h1, h2, h3 and h4 tags.

Advertisement

Answer

One way is to cycle through the header elements in order, and use their number to see if it’s in sequence with the last element

function isInOrder(className) {
  let tagn = 0,
    inOrder = true;
  document.querySelector(className).querySelectorAll('h1, h2, h3, h4, h5, h6').forEach(el => {
    if (+el.tagName.slice(-1) < tagn) inOrder = false;
    tagn = +el.tagName.slice(-1)
  })
  return inOrder;
}

console.log(isInOrder('.someClass'))
console.log(isInOrder('.someOtherClass'))
<div class="someClass">
  <h3>This is H3 tag</h3>
  <h1>Testing H1 element</h1>
  <p>Hey this is p tag</p>
  <h3>This is H3 tag</h3>
  <h2>I am H2</h2>
  <h3>This is H3 tag</h3>
  <p><b>I am Bold</b></p>
  <h4>I am H4<br></h4>
</div>

<div class="someOtherClass">
  <h1>Testing H1 element</h1>
  <h2>I am H2</h2>
  <h3>This is H3 tag</h3>
  <p>Hey this is p tag</p>
  <h3>This is H3 tag</h3>
  <h3>This is H3 tag</h3>
  <p><b>I am Bold</b></p>
  <h4>I am H4<br></h4>
</div>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement