Search code examples
javascripthtmltooltip

Pass a function to a tooltip


I am printing tags that are related to a post and the result looks like the following:

function getTag(){
  
  return "browse posts related to" + this.innerHTML;

}
span, a{
  background: red; 
  color: #fff; 
  margin: 3px; 
  padding: 1px;
  text-decoration: none;
}
Tags: <span title= 'getTag()'>
<a href="#"> food </a>
</span>

<span title= 'getTag()'>
<a href="#"> recipe </a>
</span>

<span title= 'getTag()'>
<a href="#"> drink </a>
</span>

I have tried passing the function getTag() to the attribute title but is not working correctly.

How do I use JavaScript to get the text content of each span element and pass the text content to the title attribute of each span element.

I will like using JavaScript to achieve this.


Solution

  • Without using any libraries, you need to work with the DOM. Place your script element at the bottom of the page.

    <script>
    var spans = document.querySelectorAll('span');
    
    for (var i = 0; i < spans.length; i++) {
      spans[i].title = 'browse posts related to ' + spans[i].innerHTML;
    }
    </script>
    

    The script is easy to understand. You tell your browser to fetch all your span elements and store them inside the variable called spans. In the next step you can loop trough each of this spans and manipulate their attributes.