Rockstar Rockstar - 1 year ago 56
HTML Question

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 title= 'getTag()'>
<a href="#"> recipe </a>

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

I have tried passing the function
to the attribute
but is not working correctly.

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

I will like using JavaScript to achieve this.

Ole Ole
Answer Source

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

var spans = document.querySelectorAll('span');

for (var i = 0; i < spans.length; i++) {
  spans[i].title = 'browse posts related to ' + spans[i].innerHTML;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download