Appending or adding new text next to current tooltip text JQuery

2.2k views Asked by At

I was wondering whether its possible to add new text next to or append text to existing text already on tooltip.

For example, I have a div tag containing tooltip text like so;

<div id="myDiv1" class="myDiv" title="This is Tooltip">body text </div>

As shown above, the current tooltip text is: This is Tooltip

What I want to do is using jquery, appned / add more text to this. For example,

This is toopltip for myDiv1

I have tried, but these don't seem to work and most don't return anything some return undefined, please help;

$('#myDiv1').attr("title",  $('#myDiv1').tooltip + "" + "\nSome new text to append");
$('#myDiv1').prop("tooltipText",  $('#myDiv1').tooltipText + "" + "\nSome new text to append");
$('#myDiv1').attr("data-original-title",  $('#myDiv1').tooltipText + "" + "\nSome new text to append");

Any help is welcomed :)

4

There are 4 answers

0
soyuka On BEST ANSWER

I'd do like this:

$('#test').attr('title', $('#test').attr('title') + '\nworld');

See jsfiddle.

I'd add that if you use a function it gives you the current element as context which can be really useful:

$('#test').attr('title', function() {
  console.log($(this).attr('title'));
});
2
Rajaprabhu Aravindasamy On

Try to use the callBack function of .attr() to accomplish your task,

$('#myDiv1').attr("title", function(_ , currentAttr){
  return currentAttr + "your text";
});
0
Shuma On
var currentVal = $('#myDiv1').attr('title');
$('#myDiv1').attr('title', currentVal + ' potatoe');

fiddle:https://jsfiddle.net/jdz5yz6k/

0
Rahul Baruri On

It's so simple,At first we need to get current title of this div. After that We have to append some text with this title.

Here is Jsfiddle Example

<div id="myDiv1" class="myDiv" title="This is Tooltip">body text </div>

Then the Jquery Code is:

$(document).ready(function(){
$(".myDiv").hover(function(e){
    $(this).attr('title',$(this).attr('title')+"This is new text that will be added");
 });
 })