I want to add a standard HTML/CSS tooltip:
<style>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text - see examples below! */
position: absolute;
z-index: 1;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
}
</style>
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
The only difference is that the item I want to add it to is being created by a library so I can’t modify the element in html to create the element with the "tooltip" class. But I know the id of the element so I can grab it from the DOM. How can I add a tooltip to an item I query from the DOM?
I have tried creating the span in the above example and adding it as a child after getting the desired element from the DOM but that didn’t work.
In my HTML I have the tooltiptext orphaned:
<span class="tooltiptext" id="tooltiptext">Tooltip text</span>
And then in javascript I wrote:
var tooltiptext = document.getElementById("tooltiptext");
tooltiptext.id = "newId"; //Another StackOverflow question said I should to this
var anchor = document.getElementsByClassName("tooltipTarget")[0]; //Debugging shows I'm getting the correct element
anchor.appendChild(tooltiptext);
anchor.classList.add("tooltip");
3
Answers
You can create a cool tool tip without js in it looks great.
This is an example of how you can achieve it
I hope it helped you
Since you say "standard HTML/CSS tooltip".
The standard HTML tooltip is created by using the
title
attribute on any HTML element.So if you got the ID of the element that you want to add the tooltip to, you can do this: