Solution 1 :

console.log(document.querySelector('a~c+b~c').innerText)
<a></a>
<c>incorrect</c>
<b></b>
<c>correct</c>
<b></b>
<a></a>
console.log(document.querySelector('d~c+a~c').innerText)
<a></a>
<b> </b>
<c> </c>
<c>incorrect</c>
<a></a>
<c>incorrect</c>
<b> </b>
<d> </d>
<b> </b>
<a></a>
<c>incorrect</c>
<a></a>
<c>correct</c>
<a></a>
<c>incorrect</c>
<d> </d>

Solution 2 :

To select the <c>correct</c>, you can use:

document.querySelector('b+c');

This selects all c directly following a b.

If you want to select all elements that lie between two elements, you can’t use CSS for this.

Its possible with a little javascript though:

// selects all 'c' following an 'a'
for (const element of document.querySelectoAll("a+b")) {
  // checks if the next element after 'c' is 'b'
  if (element.nextSibling().tagName == "b") {
    // prints every 'c' that follows an 'a' and has a 'b' after
    console.log(element);
  }
}

Problem :

Let’s say I have this html:

    <a></a>
    <b> </b>
    <c> </c>
    <c>incorrect</c>
    <a></a>
    <c>incorrect</c>
    <b> </b>
    <d> </d>
    <b> </b>
    <a></a>
    <c>incorrect</c>
    <a></a>
    <c>correct</c>
    <a></a>
    <c>incorrect</c>
    <d> </d>

How can I select <c>correct</c> which is between <a> and <d>
I thought about something like this:

document.querySelector('a~c.d~c');

But it doesn’t work. Do you have any ideas how can I achieve this ?

Comments

Comment posted by Umutambyi Gad

maybe typo here –>

Comment posted by Krzysztof Kaczyński

@Gad I do not understand

Comment posted by David Thomas

You spelled “document” wrong, which results in an error.

Comment posted by Krzysztof Kaczyński

This is exactly what I want. Thank you mate

Comment posted by Krzysztof Kaczyński

This will work for this case, but my case is much more complicated and i have to select element which is between two another elements

Comment posted by David Thomas

Then show enough of your real html that we can understand and reproduce your problem. Correct the spelling mistakes and see if that helps. Are there any reported errors in your console? Show them.

By