How to add custom CSS in the case of missing CSS selectors

Sometimes you need some custom CSS, but you realize the element that you want to apply the style on is without any CSS selector, and you don’t know how to target that element

The solution is adding a CSS class to every element of the DOM that doesn’t have it.
The code to do so is very simple:
add_filter( 'the_content','jose_cs_add_selectors' );
//Add CSS selectors where there aren't
function jose_cs_add_selectors( $content ){
    if( !class_exists( 'DOMDocument' ) || !function_exists( 'libxml_use_internal_errors' ) ) return;
    $dom = new DOMDocument();
    libxml_use_internal_errors( true );
    $dom->loadHTML( '<html><head></head><body>'.do_shortcode( $content ) ).'</body></html>';
    $elements = $dom->getElementsByTagName( '*' );
    $n = 0;
    foreach( $elements as $element ){
        $class_name = $element->getAttribute( 'class' );
        if( !$class_name || '' === $class_name ){
            $tag_name = $element->tagName;
            if( in_array( $tag_name,array( 'html','head','body' ) ) ) continue;
            $innerTEXT = $element->textContent;
            $new_class = $innerTEXT && '' !== $innerTEXT ? 'css-sel-'.esc_attr( $tag_name ).'-'.substr( md5( $innerTEXT ),0,6 ) : 'css-sel-'.esc_attr( $tag_name ).'-'.substr( md5( $n ),0,6 );
            $element->setAttribute( 'class',$new_class );
    $content = $dom->saveHTML();
    $content = str_replace( '<html><head></head><body>','',$content );
    $content = str_replace( '</body></html>','',$content );
    return $content;
We add our function to the filter hook the_content.
In our function, we first check if the server provides the PHP module that we need to get the DOM object by the content.
Then we check every DOM element and if it hasn’t any CSS class, we add it.

You can add the code above in the functions.php of your child theme or in a functional plugin.

If you don’t have any child theme and you need a functional plugin, you can easily create with Plugin Builder.

Or if you prefer it, you can directly download the plugin CSS Selectors that you find on the official WordPress repository.