Search code examples
javascripthtmltooltip

Change title attribute of dynamically generated html element for tooltip


I have a dynamically generated HTML element that includes a title attribute which appears in a tooltip when hovering, like:

<div title="tooltip text" class="classname" id="identifier"></div>

I would like to change the contents of the title attribute using javascript code set to run as part of the HTML render. Currently, my code is as follows:

var changeTooltip = function(){
     var TooltipElement = document.getElementsByClassName("classname");
     if (TooltipElement.title = "tooltip text"){
         TooltipElement.title = "new message";
     };
};

window.onload = changeTooltip();

This code leaves the original string in the div's title attribute once the page renders fully. Can anyone explain why, and possibly show the correct way? Note that I must use JS, I cannot use JQuery.


Solution

  • getElementsByClassName() (note the plural Elements) returns a list of elements. Loop through that:

    var changeTooltip = function(){
      var TooltipElements = document.getElementsByClassName("classname");
      
      for ( var i = 0; i < TooltipElements.length; ++i )
      {
        var TooltipElement = TooltipElements[i];
          
        if (TooltipElement.title == "tooltip text")
          TooltipElement.title = "new message";
      };
    };
    
    changeTooltip();
    .classname:after {
      content: attr(title);
      font-style: italic;
    }
    <div title="tooltip text" class="classname" id="identifier">Title: </div>
    <div title="other text" class="classname" id="identifier2">Title: </div>

    Finally, you need to change:

    window.onload = changeTooltip();
    

    to

    window.onload = changeTooltip;
    

    so that the function doesn't run until everything is loaded.