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.
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.
The reason is that as the function name suggests, getElementsByClassName
returns a list of element S , not a single element. If you know the specific element (the div element) you want to modify is the first / only element that will match the criteria, you can access it with [0]
. Try:
var TooltipElement = document.getElementsByClassName("classname")[0];
Also, since your div has an ID, you'd actually be better off with:
var TooltipElement = document.getElementById("identifier");
Always prefer using an ID when you're targeting a single, specific element. It's is much more concise, accurate and performs better.
See working example:
var TooltipElement = document.getElementById("identifier"); TooltipElement.title = "new title";
<div title="tooltip text" class="classname" id="identifier">Some text</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.