I've got a situation that has turned my mind to mush and could use some real help.
I'm pulling in an ad from Google's ad management system, Doubleclick For Publishers (DFP), using this code:
<script type='text/javascript'>
GA_googleFillSlot("TEST_960x300");
</script>
Apparently Google auto-generates a DIV around said ad. I'm detecting if an ad exists (therefore above DIV) with this:
<script type='text/javascript'>
if(document.getElementById('google_ads_div_TEST_960x300_ad_container')){
document.getElementById('google_ads_div_TEST_960x300_ad_container').setAttribute("class", "billboard");
}
//For IE since it seems DFP outputs a different div for IE.
if(document.getElementById('google_ads_div_TEST_960x300')){
document.getElementById('google_ads_div_TEST_960x300').setAttribute("class", "billboard");
}
</script>
When an ad is present I need to put the following line inside this elusive DIV element
<input type="image" id="expand_button" src="test_btn_expand.png" />
which will show a button on top of the ad allowing a user to shrink/expand the ad with said button. Everything is working like a champ but I cannot figure out how to get the above button inside Google's DIV.
Any thoughts?
1 Answer 1
There is more than one way to do that.
First, you can edit the contents of any element by using .innerHTML, however be aware that this is destructive - it removes the old contents and adds the new contents, even if you use innerHTML += ''. That is probably bad in your case because if the contents contain an iframe it may load it again, and if any properties/events have been added to any of the elements inside the container, they will be destroyed.
Example:
var el = document.getElementById('google_ads_div_TEST_960x300_ad_container');
el.innerHTML += '<input type="image" id="expand_button" src="test_btn_expand.png" />';
Second, you can append a newly created element instead of editing the whole innerHTML.
The following code uses appendChild to add a new element. It is less pretty but non-destructive:
var el = document.getElementById('google_ads_div_TEST_960x300_ad_container');
var input = document.createElement("input");
input.type = "image";
input.id = "expand_button";
input.src = "test_btn_expand.png";
el.appendChild(input);
JQuery can append an element in a prettier way:
$('#google_ads_div_TEST_960x300_ad_container').append(
'<input type="image" id="expand_button" src="test_btn_expand.png" />'
);
2 Comments
e.innerHTML += "". Do mind that you can do e.innerHTML = e.innerHTML + "whatever".
container.appendChild(element)or.innerHTML = "<input ...>". Pick and choose.