I want to add a custom attribute to the main div of a node only on teaser view mode. e-g

<div class="node" tarbot="left"> </div>    

I need to add tarbot attribute to the main div of a node to apply a JS function. I want to affect only teaser view mode with my Function, not Full content display.

  • Is it custom field or any entity field?
    – Ajay Reddy
    Commented Oct 10, 2017 at 12:40
  • 1
    You should be able to add custom attributes via #attributes key in the build array before it is sent for rendering.
    – Kevin
    Commented Oct 10, 2017 at 14:26
  • 1
    @Kevin How I can. could you provide me a format or context? Commented Oct 11, 2017 at 6:11

2 Answers 2


We can use preprocess function to change OR add an attribute to our node main div.

function MYMODULE_preprocess_node(&$variables){

  // Array of aatributes which we want to pass to the node div.
  $attr_array = ['tarbot' => 'value']; 

  // Condition for teaser format.
  if ($variables['teaser'] == TRUE) { 

    $variables['attributes_array'] = $attr_array;   

by using this function we will get our node div in this form

<div class="node" tarbot="value"> </div>

In {THEMENAME}.theme file(d8) or template.php file(d7) under your theme, you can use template_preprocess_node function and add the extra attributes to node by checking the view mode.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.