Can I conditionally call a library based on HTML element?
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.