Style span element after another interval without text content between

I would like to create a CSS rule for the style of spanelements that immediately follow some other range and there is no text content between them. So I want a style <span class="bar">Second</span>in this example:

<span class="parent">
  <span class="foo">First</span>
  <span class="bar">Second</span> <!-- this one! -->
</span>
<span class="parent">
  <span class="foo">Third</span>
  Some text.
  <span class="bar">Fourth</span> <!-- but not this! -->
</span>

I tried using both +( adjacent ) and ~( general ) combinators without success:

/* colours both "Second" and "Fourth" */
span.foo+span.bar {
  color: red;
}

I also tried several pseudo-classes:

/* colours "Third", "Some text." and "Fourth" */
span.parent :only-of-type {
  color: red;
}

I am looking for some working solution in pure CSS. It may use experimental features (e.g. :has), but they must be supported by the Chrome browser.

+4
source share
1 answer

<span> </span> :

<span>...</span><span>...</span>

textnode - , .

, :

  • , <span>... a <span>?
  • - textnode, <span>... ( )?

true, <span>.

:

var parents = document.getElementsByClassName('parent');

for (var i = 0; i < parents.length; i++) {
    var spans = parents[i].getElementsByTagName('span');
    
    for (var j = 1; j < spans.length; j++) {

        // Checks preceding textNode for readable text
        var followsWhitespace = (/^\s*$/).test(spans[j].previousSibling.textContent);

        // Just in case there is no preceding textNode at all
        if (spans[j].previousSibling.nodeName === 'SPAN') {
            followsWhitespace = true;
        }

        // Identifies preceding element
        var previousElementName = spans[j].previousElementSibling.nodeName;

        if ((previousElementName === 'SPAN') && (followsWhitespace === true)) {
            spans[j].classList.add('follows-span');
        }
    }
}
.follows-span {
font-weight: bold;
color: rgb(255, 0, 0);
}
<span class="parent">
  <span class="foo">First</span>
  <span class="bar">Second</span> <!-- this one! -->
</span>
<span class="parent">
  <span class="foo">Third</span>
  Some text.
  <span class="bar">Fourth</span> <!-- but not this! -->
</span>
Hide result
+2

Source: https://habr.com/ru/post/1687372/


All Articles