3

I'm pretty new to jquery in particular and js in general, so I hope I didn't make a silly mistake. I have the following js code:

var speechText = "Purpose of use:<br/>"; 
speechText += "<script>$(function(){$(\".simple\").tooltip();});</script>";
speechText += "<a href=\"#\" class=\"simple\" title=\"day to day use\" data-placement=\"top\" data-toggle=\"tooltip\">simple use</a>";
speechElement.innerHTML = speechText;

This function changes the content of an element on the html page. When calling this function everything works, including displaying the link "simple use", but the tooltip doesn't appear. I tried writing the exact thing on the html document itself, and it worked. What am I missing?

m144
  • 305
  • 3
  • 13

1 Answers1

4

First, Script tags inserted into the DOM using innerHTML as text, will not execute. See Can Scripts be inserted with innerHTML. Just some background on script tags, they're parsed on pageload by default in a synchronous manner meaning beginning with earlier script tags and descending down the DOM tree. However this behaviour can be altered via defer and async attributes, best explained on David Walsh's post.

You can however create a script node, assign it attribute nodes and content and append this node to an node in the DOM (or another node that is inserted into the DOM) as suggested by an answer in the aforementioned SO link (here: SO answer).

Secondly, You don't need to inject that piece of JavaScript into the DOM, you can just use that plugin assignment in the context of the string concatenation. So as an example you might refactor your code like this:

HTML

var speechText = "Purpose of use:<br/>";
speechText += "<a href=\"#\" class=\"simple\" title=\"day to day use\" data-placement=\"top\" data-toggle=\"tooltip\">simple use</a>";
speechElement.innerHTML = speechText;
$(function(){ $(".simple").tooltip(); });
Community
  • 1
  • 1
cjross
  • 636
  • 1
  • 5
  • 10