Add tooltip to list item

Viewed 463

I dynamically add text to a list like such:

var list = document.getElementById('list');
var entry = document.createElement('li');
entry.appendChild(document.createTextNode('text'));
list.appendChild(entry);

I want to modify this so that for the list item, when you hover over the item it will show a tooltip with some text. I found example online:

<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>

But I don't know how to combine it with the li item

2 Answers

Set the title attribute:

var list = document.getElementById('list');
var entry = document.createElement('li');
var text = document.createTextNode('text');
entry.appendChild(text);
entry.title = "Tooltip text";
list.appendChild(entry);

You can use bootstrap to display tooltip. Please use following code as a reference:

let list = document.getElementById('list');
let counter = 5;
while(counter-->=0) {
  var span = document.createElement('text');
  span.setAttribute('data-toggle', 'tooltip');
  span.setAttribute('title', 'This is tooltip');
  span.textContent = 'text';
  
  var entry = document.createElement('li');
  entry.appendChild(span);
  list.appendChild(entry);
}
$("#list li text").tooltip();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

<div id="list"></div>

Related