Reputation: 1417
I have jScript that is creating dynamic html, and its being called like this:
<span id='thisNeedsToBeHere'><!-- notice arbitrary id name-->
<script type='text/javascript'
data-parm-one = 'foo'
data-parm-two = 'bar'
src='/dirOne/myJavascript.js'>
</script>
</span>
This script needs the ability to be placed inside of any type of DOM element.
Inside of myJavascript.js we currently have the following:
var wrapper = document.createElement('div');
wrapper.innerHTML = 'blah blah blah';
jQuery( $(document.currentScript).parent()[0].tagName
+ '#'
+ $(document.currentScript).parent()[0].id
).append(wrapper);
and this will append the wrapper to the parent element.
This works, but notice i have to assign an arbitrary id to the parent element, in this case i call it thisNeedsToBeHere. Without an ID, it wont work.
<div id=''><!--this wont work because there is no div id defined-->
<script type='text/javascript'
data-parm-one = 'foo'
data-parm-two = 'bar'
src='/dirOne/myJavascript.js'>
</script>
</div>
First thing I tried was using $(this).append(wrapper) but got this message back:
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
Is there a better way to append html to a parent element where we may not have an id?
Upvotes: 1
Views: 213
Reputation: 193261
Looks like you overcomplecated this. You don't need to construct CSS selector to select parent element as parentNode.tagName + '#' + parentNode.id
, since you already have one available as parent()
:
var wrapper = document.createElement('div');
wrapper.innerHTML = 'blah blah blah';
$(document.currentScript).parent().append(wrapper);
In fact, you don't even need wot worry selecting parent element to append to, with jQuery you can use after
method:
$(document.currentScript).after(wrapper);
Upvotes: 3