Reputation: 2013
I have a jquery function that returns the html for a randomized advertisement.
function getAd() {
document.write( '<div>Some randomized ad html</div>' );
}
To insert the ad, I have this in my html file:
<div><script>getAd();</script></div>
This works, however, I'm trying to replace the document.write() code with something safer, like append(). So I'm trying this:
function getAd() {
$(this).append( '<div>Some randomized ad html</div>' );
}
However, $(this) is the window and not the div.
I also tried this:
function getAd(elem) {
$(elem).append( '<div>Some randomized ad html</div>' );
}
And in the html, I pass this:
<div><script>getAd(this);</script>
But once again, $(elem) is a window rather than the div. (In both of these cases, I get an "Cannot read property 'createDocumentFragment' of undefined" error.)
I realize I can assign an id to the div and then pass the id to the getAd() function, but I have hundreds of these calls on the website (and sometimes several on the same page) and I would prefer not to have to assign and then pass an id every time I call this function.
Is there a way the calling function can determine the calling element so it can append the html?
Thanks!
Upvotes: 2
Views: 49
Reputation: 4365
You can add a common attribute (or a class) to all your elements:
<div random-ad>
And then, call your function using $.each()
:
function getAd(elem) {
$(elem).append( '<div>Some randomized ad html</div>' );
}
$(document).ready(function(){
$('[random-ad]').each(function(){
getAd(this);
});
});
Upvotes: 4