Search code examples
htmlcssbehat

How to check for text created by CSS?


I have the following HTML:

<h4 id="myModalLabel"></h4>

I set the content in CSS:

#myModalLabel::after {
    content: "gebeurtenis";
}

jsFiddle

This way, Behat can't seem to find the text when running this for example:

  Scenario: Viewing gebeurtenis
    Given I am on "hrm/calendar"
    Then I should see "gebeurtenis"

The result:

Then I should see "gebeurtenis"        # HRMContext::assertPageContainsText()
      The text "gebeurtenis" was not found anywhere in the text of the current page. (Behat\Mink\Exception\ResponseTextException)

How can I make it so this test will be successfull?


Solution

  • May I suggest a little trick, css att(), to use a text in a pseudo and at the same time have it accessible in the DOM

    h4:after {
        content: attr(data-txt);
    }
    <h4 id="myModalLabel"  data-txt="gebeurtenis">Here we go ... </h4>

    If you still need to look for a text that might be (or you know) in a css rule, then you can do like this, though to scan all elements looking for "text hidden in pseudo css" might not be that speedy.

    var element = document.getElementById('div_1'),
        style = window.getComputedStyle(element,':after'),
        value = style.getPropertyValue('content').replace(/^\"|\"$/gm,''),
        result = document.getElementById('result');
    
    if(value.length > 0) {
        result.innerHTML = 'Found in css: ' + value;
    }
    #div_1 {
       color: red;
    }
    #div_1:after {
       content: 'world';
       color: blue;
    }
    #result {
       margin-top: 20px;
    }
    <div id="div_1">hello </div>
    <div id="result"></div>