How can I add classes to the rendered "body" field on a content type? Preface: I don't often work with Drupal, so I may not be using the correct terminology or fully understand the stack. Please bear with me, I'll do my best to be as clear as possible.

I want to filter the rendered output of the primary "Body" field on a "Basic Page" (or "Article," any content type really) to add some classes to various elements. This would be the field labeled "Body" at /node/add/page. I'd like to achieve this using DOMDocument in my .theme file, but I'm having trouble figuring out what the correct "hook" is to tie in to.

So ultimately the goal would be a function something like the following (which is partially psuedo code):

function my_theme_body_alter(&amp;$content) {
    $DOM = new DOMDocument();

    $DOM-&gt;loadHTML(mb_convert_encoding($content, "HTML-ENTITIES", "UTF-8"), LIBXML_HTML_NODEFDTD);

    $anchors = $DOM-&gt;getElementsByTagName("a");

    foreach ($anchors as $anchor) {
        $existing_classes = $anchor-&gt;getAttribute("class") ? $anchor-&gt;getAttribute("class") : "";

        $anchor-&gt;setAttribute("class", "button {$existing_classes}");
    }

    $content = $DOM-&gt;saveHTML($content);

    return $content;
}


To be absolutely clear, I want to modify the output (on the front end) of this field:



What is the name of the hook I'm looking for, or how can I locate it myself?
note:I have tested it in my machine and it works 100%



the Hook_preprocess_node is gonna be executed before the rendering of any node of any content-type, you have to apply your logic here but be sure to apply it only of the body field exist otherwise you'll get an error if some content type doesn't have this field, then inject the updated dom into the node.html.twig template using the $varaibles that has been passed by ref to the current hook:


&lt;?php
/**
* Implements  hook_preprocess_hook
*/
function test_preprocess_node(&amp;$variables){
 // 1. Getting the current node.
 $node = $variables['node'];


 //2. Apply this logic to all nodes that have a body field
 if( $node-&gt;hasField('body')){

   //3.Get the body field
    $body = $node-&gt;body-&gt;value;

    //4.Apply som logic on the body field
     $body = updateBodyDom($body);

   //5.injecting the result into the node template (ex: node.html.twig)
   $variables['body'] =  $body ;
 }

}


function updateBodyDom($body){
 $DOM = new DOMDocument();

 $DOM-&gt;loadHTML(mb_convert_encoding($body, "HTML-ENTITIES", "UTF-8"), LIBXML_HTML_NODEFDTD);

 $anchors = $DOM-&gt;getElementsByTagName("a");

 foreach ($anchors as $anchor) {
   $existing_classes = $anchor-&gt;getAttribute("class") ? $anchor-&gt;getAttribute("class") : "";
   $anchor-&gt;setAttribute("class", "button {$existing_classes}");

   //kint($anchor-&gt; getAttribute('class')); die();
 }

 $content = $DOM-&gt;saveHTML( );
 return   $content;
}




in your templates folder create node.html.twig, to render the
injected body :


{{ body }}