Roger W Roger W - 2 months ago 6
HTML Question

Dynamically adding jquery into div

Apologies, I know there are a number of questions along the same lines and they've helped me a lot but I'm still falling at the final hurdle.

I'm trying to dynamically add some jQuery into a div using this:

function displayPage(position,page){
// position arrives looking something like '#pageW20' - ignore quotes
// page arrives looking something like 'pages/benefits.html' - ignore quotes
var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
var str = "<script type='text/javascript'>";
/* Build the script which typically looks like this:-
<script type='text/javascript'> $( "#pageB15" ).load( "pages/benefits.html", function(){openLetter()}); </script>
*/
str += '$( ' + '"' + position + '"' +' ).load(' + page + ', function(){openLetter()})';
str += '<';
str += '/script>';
alert(str); // Works to here, alert churns out expected output.
//$('"' + position + '"').append(str); // Tried this, end up with syntax error
myDiv.appendChild(str); // This gives Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
}


The last two lines show the errors I'm getting trying 2 different methods. Any clues.
Thanks appreciate your interest.

Update: Here's what I get in my console at the alert() stage which is what I was hoping for -

<script type='text/javascript'>$( "#pageW20" ).load("pages/work.html", function(){openLetter()})</script>

Answer

I cannot understand why you are trying to create and append a script on the fly like described in the comments.

The error you get is:

myDiv.appendChild(str);

But appendChild requires as first parameter a node.

So if you need to continue in this direction you have to create a script node element and after you can append it to the html like in my example:

function displayPage(position, page) {
  var pos = position.substring(1); // New variable without the '#' that appears in the first character of position
  var myDiv = document.getElementById(pos); // Find the div, typically equates to a div id similar to 'pageW20'
  var str = '$( ' + '"' + position + '"' + ' ).load("' + page + '", function(){openLetter()})';
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.text = str;
  myDiv.appendChild(s);
}

displayPage('_XXX', 'page');

console.log(document.getElementById('XXX').outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="XXX"></div>

Comments