Can I conditionally call a library based on HTML element? I would like to use DataTables.js for tables created by content editors in the main body field of a content type. I already have the library installed in my libraries.yml.

I had an idea that I could avoid calling the library globally, but instead have it only be called on a page that has an HTML &lt;table&gt; element rendered.

That idea came from drupal.org documentation here, which offers up this code example for the hook_element_info_alter() function:

function fluffy_element_info_alter(array &amp;$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'fluffiness/fancy_table';
  }
}


However when I checked into the theme.api, I saw this code is intended for people making modules and indeed the documentation section I saw it in was for modules.

Can I use this same or similar bit of code in my theme_name.theme file to apply to all nodes? Is there something else I should do instead?

Thanks for any advice you can offer.
hook_element_info_alter won't suit in this situation because you are trying to do something based on the value of a body field, which is just 'text' as far as Drupal is concerned. Element in the Drupal world is different. But here is an approach to your problem.

You can implement hook_preprocess_node and check if the body field value contains &lt;table - and if there is a hit, then attach the library:

use Drupal\Component\Utility\Unicode;

function mytheme_preprocess_node(&amp;$variables) {
  $node = $variables['node'];
  $match = Unicode::strpos($node-&gt;field_body-&gt;value, '&lt;table');

  if ($node-&gt;field_body-&gt;value &amp;&amp; $match !== FALSE) {
    // next line is just an example
    $variables['#attached']['library'][] = 'mytheme/libraryname';
    $variables['#attached']['library'][] = 'mytheme/datatables';
  }
}


This will only attach the library to a node being rendered IF the node body field has a value, and within it, there is a match for an opening table tag.

The use statement should go at the top of your mytheme.theme file.

strpos has a caveat:


  Note that a return value of 0 is not the same as FALSE.


So if you plan on using this a little more elsewhere, take note.