How to pass a Javascript function in a dynamically created div - javascript

I want to pass a javascript function to a dynamically created div, like I am attempting below. If I replace the script string with an ordinary string this works, but is there a way to pass a JS script in createTextNode?
newDiv = document.createElement("div");
newContent = document.createTextNode("<script type=\"text/javascript\">var pager = new Pager(3); pager.init(); pager.showPageNav('pager', 'pageNavPosition'); pager.showPage(1); </script>");
newDiv.appendChild(newContent);
TIA

A <script> tag is not a text node.
You need to create a <script> element using document.createElement.
However, you should not do this, unless you're trying to load an external script file dynamically (eg, JSONP)

var js=document.createElement('script');
js.setAttribute("type","text/javascript");
js.appendChild(document.createTextNode(" var pager = new Pager(3); pager.init(); pager.showPageNav('pager', 'pageNavPosition'); pager.showPage(1); "));
var newDiv=document.createElement("div");
newDiv.appendChild(js);
document.appendChild(newDiv);

Related

Variable attributes disapearing when put inside div

Probably a simple question but I can't seem to find the answer. I am dynamically creating a page where I can share twitter links.
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
etc..
I then append it to the div I want such as
$('#doc').append('<img(miscellaneous HTML)>'+twitter)
What I have above works but for CSS formatting purposes I want the image with the twitter share button to be a sub-block. So I create something like this
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
But when I do this it seems all the attributes of the twitter var are lost, only printing http: // twitter.com/share on the page instead of the button.
I feel it's probably a basic concept I am forgetting.
You are tring to concatenate a DOM object and a String via this code
$('#doc').append('<div id="innerblock'+i+'"><img(miscellaneous HTML)>'+twitter+'</div>)
This twitter variable contains a DOM object and the rest of the append block is String.
Try this:
var div = $('<div id="innerblock'+i+'"><img(miscellaneous HTML)></div>').append(twitter);
$('#doc').append(div);
What I would do is instead of appending the HTML instead you can create the innerblock div and the img tags using document.createElement and append the twitter to the img and the img to the div before appending it all to #doc
You can not concatenate a sting and a DOM node.
var div = $("<div id="innerblock'+i+'">").append("<img />").append(twitter);
or
var div = $("<div/>", {id : "innerblock" + i).append("<img />").append(twitter);
Try substituting .outerHTML String of twitter for DOM element Object twitter ; also adding closing sing quote ' at end of string parameter provided to .append()
var twitter = document.createElement('a');
twitter.setAttribute('href', 'http://twitter.com/share');
twitter.setAttribute('class', 'twitter-share-button twitter-tweet');
twitter.setAttribute('data-text', 'I liked this image');
var i = 0;
$('#doc').append('<div id="innerblock'+i+'"><img />'+twitter.outerHTML+'link</div>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="doc"></div>

Javascript - Insert element at script position

How do I insert element at script location (not to rely on div's id or class), for example
<div class="div">
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
where addDivSayHello.js will insert div child <div>hello</div>, result example:
<div class="div">
<div>hello</div>
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
I tried searching inside Stackoverflow but found nothing.
You can use insertBefore method. Something like this:
var div = document.createElement('div'), // Create a new div
script = document.scripts[document.scripts.length - 1]; // A reference to the currently running script
div.innerHTML = 'Hello'; // Add some content to the newly-created div
script.parentElement.insertBefore(div, script); // Add the newly-created div to the page
A live demo at jsFiddle. Notice, that you can use external scripts as well.
You could use insertAdjacentHTML: https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML
var node = document.querySelector('script[src="js/addDivSayHello.js"]');
node.insertAdjacentHTML('beforebegin', '<div>hello</div>');
$("div.div").prepend('<div>hello</div>');
You have to call the script at some point
i like to use jquery to add an element http://api.jquery.com/append/
you have to say where do you want to add :
$(".div")
and what should happen there:
.append("<div>Hello</div>")
so its look like that:
$(".div").append("<div>Hello</div>")
Another solution that doesn't wrap everything inside a div and that can be re-used several times without implications:
function insertHtmlToDocumentAtCurrentScriptPosition(htmlStr)
{
var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parentTag = scriptTag.parentNode;
parentTag.innerHTML += htmlStr;
}
The function takes html as string, so call it like:
insertHtmlToDocumentAtCurrentScriptPosition(`<p>Hello</p>`);

native javascript equivalent to jquery.append when iframes are present

I am trying to use native javascript to append a string of html to a target div. This works fine using:
var selector = document.getElementById('divid');
var str = '<div><h1>string of html content</h1></div>';
selector.innterHTML += str;
Except whenever the document contains an iframe it seems to hide the frame when appending the innerhtml. I tried a work around as follows:
var selector = document.getElementById('divid');
var str = '<div><h1>string of html content</h1></div>';
var div = document.createElement('div');
div.innerHTML = str;
selector.appendChild(div);
This works but now I am creating an unnecessary div container, is there a way to do this without creating a new element that won't erase the iframe?
Except whenever the document contains an iframe it seems to hide the frame when appending the innerhtml
See "innerHTML += ..." vs "appendChild(txtNode)" for the reason - modifying innerHTML creates a new iframe that reloads. Also have a look at What is better, appending new elements via DOM functions, or appending strings with HTML tags?
This works but now I am creating an unnecessary div container
Just don't create an extra div, you have one in your HTML anyway:
var selector = document.getElementById('divid');
var div = selector.appendChild(document.createElement('div'));
div.innerHTML = '<h1>string of html content</h1>';
is there a way to do this without creating a new element that won't erase the iframe?
You can also use the native insertAdjacentHTML method which is the equivalent to jQuery's append with a HTML string:
var selector = document.getElementById('divid');
selector.insertAdjacentHTML('beforeend', '<div><h1>string of html content</h1></div>');
This seems to work.
var parser = new DOMParser();
var el = parser.parseFromString(str, "text/html");
selector.appendChild(el.childNodes[0]);

Adding Dynamically created div data to a new empty variable

I am trying to push the data of a dynamically created div
<div id="paging_inner"></div> to the newly created variable
var content= '';. I commented the code which I tried there in my script.
Is there any jQuery method for inserting the data (without using the jQuery .append() method)?
This is what I tried, but I need help:
http://jsfiddle.net/QNZDX/19/
Do you mean:
var div=$('<div id="paging_inner"></div>');
for(...) {
...
}
$('#paging').html(div);
One option would be , creating content inside for loop adding it to a variable, and appending it to the div, after loop, like:
var div=$('<div id="paging_inner"></div>');
var insertContent = '';
for(i=0;i<maximages;i++) {
insertContent += '<a id="page_'+(i+1)+'" data-index="'+(i+1)+'"><span></span></a>';
}
$('div').append(insertContent);
Or did you mean that you want to move the content of the DIV into a variable called content?
If so, you just do this:
var content = document.getElementById("paging_inner").innerHTML;

Jquery modify div created from html before appending

I have a function that appends a div to another div.
Something like:
var div = ...some html
$("#mydiv").append(div);
However I want to do some stuff to the div I just added. Currently I want to hide a sub part of the new div, and add a object as data. Something like
var div = ...some html
$("#mydiv").append(div);
$(my new div).find(".subDiv").hide();
$(my new div).data('user',object);
But how should I get the the new div I created? Is there a way to create it and then preform these actions, and then append it? Or should I append it and then retrieve it and modify it?
Efficiency is important as this will be iterated for search results...
Thanks!
I used this as my solution thanks to Tricker:
var div = ...a lagre piece of html;
var newDiv = $(div);
newDiv.find("[show='contractor']").hide();
newDiv.data('user', userObject);
$(appendDiv).append(newDiv);
Thanks!
The way u want is like this:
var new_obj = $('<div class="subDiv"></div>');
$("#my_div").append(new_obj);
//You dont have to find the subdiv because the object "new_obj" is your subDiv
new_obj.hide();
new_obj.data('user',object);
Does .append() not return the new item?
var myNewDiv= $("#mydiv").append(div);
since it will always be the last child div, I believe you can access it via $("#myDiv div:last-child")

Categories

Resources