Skip to content Skip to sidebar Skip to footer

Selecting One Of The
Elements In A Pair By Pure Css

Is there a way to select one element, immediately following (or preceding) other by pure CSS? Foe example, hide one of in a pair:

text text

Solution 1:

The problem here is that the only thing separating your br elements is text. Sibling combinators in CSS ignore all non-element nodes between elements including (but not limited to) comments, text and whitespace, so as far as CSS is concerned, all of your paragraphs have exactly five consecutive br children each:

<p><br><br><br><br><br></p><p><br><br><br><br><br></p><p><br><br><br><br><br></p>

That is, every br after the first in each paragraph is a br + br (and by extension also a br ~ br).

You will need to use JavaScript to iterate the paragraphs, find br element nodes that are immediately followed or preceded by another br element node rather than a text node, and remove said other node.

var p = document.querySelectorAll('p');

for (var i = 0; i < p.length; i++) {
  var node = p[i].firstChild;

  while (node) {
    if (node.nodeName == 'BR' && node.nextSibling.nodeName == 'BR')
      p[i].removeChild(node.nextSibling);

    node = node.nextSibling;
  }
}
<p>text text <br><br>text text <br>text text <br><br>text text</p><p>text text <br>text text <br><br>text text <br><br>text text</p><p>text text <br><br>text text <br>text text <br><br>text text</p>

Solution 2:

This is probably unreliable, but works, at least on Firefox:

br {
  display: block;
}

br {
  display: block;
}
<p>text text <br><br>text text <br>text text <br><br>text text</p><p>text text <br>text text <br><br>text text <br><br>text text</p><p>text text <br><br>text text <br>text text <br><br>text text</p>

Post a Comment for "Selecting One Of The
Elements In A Pair By Pure Css"