javascripthtmlbootstrap-5popover

Bootstrap 5 popover html content


I am using Bootstrap 5 popover and it could not show the HTML content that I need.

I followed this link as a solution:

How to add html tag attribute in bootstrap 5 popover setAttribute()?

It was working for some of the HTML attributes like for example: data-bs-content="<h1>Hello</h1>"

But what I need to display is a table:

<table>
<tr>
  <td>A班</td>
  <td>B班</td>
  <td>C班</td>
</tr>
<tr>
  <td>John</td>
  <td>Mary</td>
  <td>Joy</td>
</tr>

My HTML:

<button type="button" class="btn btn-lg btn-danger testing" data-bs-toggle="popover" 
data-bs-content ="
<table>
<tr>
  <td>A班</td>
  <td>B班</td>
  <td>C班</td>
</tr>
<tr>
  <td>John</td>
  <td>Mary</td>
  <td>Joy</td>
</tr>
    </table>
" 
title="Popover title"
data-bs-trigger="hover"
>Click to toggle popover</button>

And the Javascript:

var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl,

   // options object as a second param
   {
      html: true
    }
  )
}) 

What am I missing? Does it require something if I want to use table in data-bs-content?


Solution

  • The bootstrap docs state:

    By default, this component uses the built-in content sanitizer, which strips out any HTML elements that are not explicitly allowed

    Meaning you need to add all table elements to the allowlist for this to function.

    Example:

    const allowList = bootstrap.Popover.Default.allowList;
    allowList.table = [];
    // tbody and thead are needed since they're automatically added by the browser if not present
    allowList.tbody = [];
    allowList.thead = [];
    allowList.td = [];
    allowList.tr = [];
    
    var popoverTriggerList = [].slice.call(
      document.querySelectorAll('[data-bs-toggle="popover"]')
    );
    var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
      return new bootstrap.Popover(
        popoverTriggerEl,
    
        // options object as a second param
        {
          html: true,
          allowList: allowList,
        }
      );
    });