Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

html - Selecting one of the <br> 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 <br> in a <br><br> pair:

<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>

and get it prosessed in the end as:

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

display: none; appled for br + br or br ~ br don't work as described above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...