Search code examples
javascripthtmlcsspseudo-elementgetcomputedstyle

How can I distingush between the content property of the ::before element being not specified at all and being specified as an empty string?


How can I check in javascript (with jQuery) if the 'content' property is set on a before or after pseudo element? In chrome, window.getComputedStyle(elem, '::before').getPropertyValue('content') returns an empty string both when 'content' is set to an empty string and when content is not set.

I have thought of one solution: set other properties such as width and height and check if the computed style is affected; I would, however, like to minimize the number of calls to getComputedStyle.

Thanks


Solution

  • Simply add an if truthy clause to test that it has some value.

    E.G:

    var before = window.getComputedStyle(elem, ':before').getPropertyValue('content');
    if(before && before!=="none"){//<-- (IE / FF fix) check it doesn't equal 'none'
        //content: is defined but it could still be an empty string
        alert("Before="+before);
    } else {
        //there is no :before content: defined at all
    }
    

    Here's the demo. Try changing the css :before content to test it.

    Also, you can reduce the code still further by using
    getComputedStyle(elem, ':before').content
    instead of
    window.getComputedStyle(elem, ':before').getPropertyValue('content').