1

I would like to add some Javascript to a HTML head like this:

var scriptInjection = "<script type='text/javascript'/>function toggleVisibility() {$('#ivuFrm_page0ivu1').contents().find('.tableContentRow').toggle()}</script/>";
$('#ivuFrm_page0ivu1').contents().find("head").each(function(){
        console.log($(this).prop("tagName"))
        $(this).append(scriptInjection);
        });

This is only appending a string though and not the script element. How can I resolve this?

2
  • 4
    that's because you're not inserting html. you're inserting a text node. &lt; means nothing to JS. if it was "<script...>", then it'd be seen as html. ditto for &gt; Commented Aug 6, 2015 at 16:04
  • 1
    Create a script tag with document.createElement(). Commented Aug 6, 2015 at 16:05

4 Answers 4

7
var script = document.createElement('script');
script.textContent = "function toggleVisibility() {$('#ivuFrm_page0ivu1').contents().find('.tableContentRow').toggle()};";
$(this).append(script);
Sign up to request clarification or add additional context in comments.

3 Comments

This worked thanks I will except when time is up. Yet I still receive a "toggleVisibility is not defined" error if i click on the button in the body with the onClick = 'toggleVisibility()'. Any ideas on that?
You probably have to rebind the function to the button After you insert the extra script tags, since the button won't refer to your new function yet.
shouldn't $.append() already create the element if passed a string? i think it just needs un-encoded.
2

In jQuery:

$('head').append(
    '<script>' +
        'function toggleVisibility() {' +
            '$(\'#ivuFrm_page0ivu1\').contents().find(\'.tableContentRow\').toggle()' +
        '}' +
    '<\/script>'
);

Comments

1
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange = function() {
// if (this.readyState == 'complete') { callFunctionFromScript(); }
}
script.src = 'your/path/to/-script.js';
head.appendChild(script);

1 Comment

OP doesn't have an external script, adding via and dom methods won't execute the textContent, jquery internally uses eval() to do that.
0

using vanilla js (no jquery)

var ajax = new XMLHttpRequest();
ajax.open("GET", "/yourpath/toyourfile.html", true);
ajaxInicial.onreadystatechange = function () {if (this.readyState == 4 && this.status == 200) {document.getElementsByTagName('head')[0].insertAdjacentHTML('beforeend', this.responseText);}}
ajaxInicial.send();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.