Mobile device in Google Tag Manager - javascript

Have the problem. Need to append the to another element on the page, but in my case, i can't append to elements (except tag ). This is my code for mobile (it works, but i don't need var textnodes = document.getElementsByTagName('body')[0]; i need something like this: var textnodes = document.getElementsByClassName('some-custom-class-name')[0];):
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
document.getElementById('class-mobile').style.display = 'block';
var nodes = document.getElementById("class-mobile");
var textnodes = document.getElementsByTagName('body')[0];
textnodes.appendChild(nodes);
}else{
document.getElementById('class-button').style.display = 'block';
var node = document.getElementById("class-button");
var textnode = document.getElementsByTagName('body')[0];
textnode.appendChild(node);
}
With desktop i have 0 problem. But is this code the only way to append my custom button to the page using GTM?

Related

Add loaded content to bottom of page

I get a page via ajax, how can I append that page to the current page?
I've looked at:
var div = document.createElement('div');
div.innerHTML = 'Your content, markup, etc.';
target.parentNode.insertBefore( div, target );
But I do not want to create a wrapper element - and just want to add the loaded page on to the bottom of the content. is this possible?
Vanilla javascript only please.
Is it it you are looking for?
var div = document.createElement('div');
div.innerHTML = 'test2';
var target = document.getElementById('target');
target.insertAdjacentElement('afterend',div);
or directly to end of body
var div = document.createElement('div');
div.innerHTML = 'test2';
var target = document.body.insertAdjacentElement('beforeend',div);

Appending html using native javaScript

I need to append some html to an existing element using pure javaScript:
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var target = document.querySelectorAll(".container-right");
var fragment = create(
'<div class="freetext"><p>Some text that should be appended...</p></div>'
);
document.body.insertBefore(fragment, document.body.childNodes[0]);
It's kind of working, but I have two questions:
How can I make sure that the html fragment is appended to the div with the class container-right and not just the body? Changing the last line to document.body.insertBefore(fragment, target); doesn't work.
How can I insert the html after the content in the target element - after the existing content - like jQuery's append()?
Any help is much appreciated.
JsFiddle here.
Well, I know this works:
let elem = document.querySelector ( 'css-selector (id or class)' )
That should give you your element. Then you do this:
elem.innerHTML = elem.innerHTML + myNewStuff;
That'll append your html to the innerHTML of the element. I tried it quickly, it works.
var target = document.querySelector(".container-right");
var p = document.createElement('p');
p.innerHTML = "Some text that should be appended...";
var div = document.createElement('div');
div.appendChild(p);
var fragment = document.createDocumentFragment();
fragment.appendChild(div);
target.appendChild(fragment);
JSFiddle
Try this:
var target = document.querySelector(".container-right");
target.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';
Based on this answer to a similar question, I have found that insertAdjacentHTML is a good fit for this kind of problems.
I haven't tested it on a Node List, but with a single node it works perfectly.
insertAdjacentHTML has a great browser compatibility (back to IE4), plus it lets you decide where you want to insert the HTML (see here).
var target = document.querySelector(".container-right");
var newContent = '<div class="freetext"><p>Some text that should be appended...</p></div>';
target.insertAdjacentHTML('beforeend', newContent);
document.querySelectorAll('.container-right').forEach(elm=>{
elm.innerHTML += '<div class="freetext"><p>Some text that should be appended...</p></div>';
});

How to get child nodes in documentFragment?

I need to know if there is a "span" in my extracted content.
Simple js part, getting selection from textarea:
...
selection = this.getWin().getSelection().getRangeAt(0);
content = selection.extractContents();
alert(content)// this gets documentFragment
alert(content.firstChild)//null
fontEl = document.createElement ("span")
fontEl.appendChild(content);
alert(fontEl.outerHTML)// works ok. but now i have 2 spans if there was one before append
there is my jsfiddle. i test changing the font-size. it works, but it is spamming spans because of this problem.
http://jsfiddle.net/DCGRg/73/
Your code isn't far off. Here's an updated demo:
http://jsfiddle.net/DCGRg/73/
Here's the relevant piece of code:
var font_size = combo.getValue();
var selection = this.getWin().getSelection();
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
var content = range.extractContents();
var fontEl = this.getWin().document.createElement("span");
fontEl.style.fontSize = font_size + 'px';
fontEl.appendChild(content);
range.insertNode(fontEl);
selection.selectAllChildren(fontEl);
}

Manipulating DOM data without affecting the view

<!DOCTYPE html>
<html><body>
<p id="intro">Hello <em id="abcd">intro</em> World!</p>
<script type="text/javascript">
var txt=document.getElementById("intro").innerHTML;
var el = document.createElement("span");
el.innerHTML = txt;
var aa = el.getElementById("abcd").innerHTML;
alert( aa );
</script>
</body></html>
The above is a simple snippet. Actually I have an HTML editor and when the user saves the data I should save only the required content. Here I am getting the content of an element and manipulating it with DOM and pass the details to the server. This way I will not change the page content (user view remains the same) and he/she will continue editing the document.
The above is a simple example but in the real case I have to remove, change and move certain elements. The above code fails el.getElementById("abcd").innerHTML. Appreciate any pointers.
You can create a hidden iframe to manipulate all your changes, thus creating a separate DOM, then simply pull back the results you want.
var iframe;
if (document.createElement && (iframe = document.createElement('iframe'))) {
iframe.name = iframe.id = "externalDocument";
iframe.className = "hidden";
document.body.appendChild(iframe);
var externalDocument;
if (iframe.contentDocument) {
externalDocument = iframe.contentDocument;
} else if (iframe.contentWindow) {
externalDocument = iframe.contentWindow.document;
}
else if (window.frames[iframe.name]) {
externalDocument = window.frames[iframe.name].document;
}
if (externalDocument) {
externalDocument.open();
externalDocument.write('<html><body><\/body><\/html>');
externalDocument.close();
/* Run your manipulations here */
var txt = document.getElementById("intro").innerHTML;
var el = document.createElement("span");
el.innerHTML = txt;
/* Attach your objects to the externalDocument */
externalDocument.body.appendChild(el);
/* Reference the externalDocument to manipulate */
var aa = externalDocument.getElementById("abcd").innerHTML;
alert(aa);
}
/* Completed manipulation - Remove iFrame */
document.removeChild(iframe);
}
I have it working here:
http://jsfiddle.net/ucpvP/
Try using jQuery like given below.
function SaveData() //Your add function
{
var txt=$("#intro").html();
$(document).append("<span id='abcd'>" + txt+ "</span>");
var aa = $("#abcd").hmtl();
alert(aa);
}
You can use a DOM Element that is never appended to the DOM.
I use this 'cleanup' function:
function cleanup(str){
var tester = document.createElement('div'),
invalid, result;
tester.innerHTML = str;
//elements I don't allow
invalid = tester.querySelectorAll('script,object,iframe,style,hr,canvas');
// the cleanup (remove unwanted elements)
for (var i=0;i<invalid.length;(i+=1)){
invalid[i].parentNode.removeChild(invalid[i]);
}
result = tester.innerHTML;
tester = invalid = null;
//diacritics to html-encoded
return result.replace(/[\u0080-\u024F]/g,
function(a) {return '&#'+a.charCodeAt(0)+';';}
)
.replace(/%/g,'%25');
}
//usage:
cleanup(document.getElementById("intro").innerHTML);
You can extend the function with your own code to remove, change and move certain elements.

Dynamically replace HTML element in UIWebView

I have some HTML loaded in WebView like this:
<html><head></head><body>before <myTag>Content</myTag> after</body></html>
I want to replace element myTag with custom text so it should look like:
<html><head></head><body>before ____MY_CUSTOM_TEXT___ after</body></html>
Also I can't change initial HTML.
How I can do this with JavaScript?
My not finished code:
var elements = document.getElementsByTagName( 'myTag' );
var firstElement = elements[0];
var parentElement = firstElement.parentNode;
var html = parentElement.innerHTML;
parentElement.innerHTML = html.replace(?????, '____MY_CUSTOM_TEXT___');
I don't know how to get string value of element to replace (?????).
Here you go:
var txt = document.createTextNode('____MY_CUSTOM_TEXT___');
parentElement.replaceChild(txt, firstElement);

Categories