Home > other >  Error appending SCRIPT HTML tag through jQuery
Error appending SCRIPT HTML tag through jQuery

Time:09-14

I'm managing a WordPress website using jQuery v3.6.0 jQuery.migrate, it triggers a very weird error every time a SCRIPT code is appended to the page.

For example:

jQuery('body').append('<script>console.log("test")</script>'); 

The returned error is

Uncaught TypeError: n.head.appendChild(...) is undefined

Anyone has ever faced anything similar? Any hint on how to solve?

CodePudding user response:

Try separating the string <script> into unrecognizable by compiler by splitting it to two words.

jQuery('body').append('<sc'   'ript>console.log("test")</scri'   'pt>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

CodePudding user response:

Here's the answer solving the problem by NOT using jQuery.

$('.the_element')[0].innerHTML = contents;

let scripts = $('.the_element')[0].getElementsByTagName("script");
for (let i = 0; i < scripts.length; i  ) {
    eval(scripts[i].innerText);
}

(honestly I still don't understand what jQuery might have on that customer website..!)

  • Related