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);
Related
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?
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>';
});
I need to wrap up the body content inside a div dynamically. I tried the below code and i am getting, 'newDiv.append function is undefined'. I tried with setTimeout as well and checked after the jquery file loads made for loop to get loaded. Still getting the same error.
function initiate() {
var jq_script = document.createElement('script');
jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js');
document.head.appendChild(jq_script);
var newDiv = document.createElement('div')
newDiv.setAttribute('id', 'wrapper');
var bodyChildren = document.body.childNodes;
for (var i = 0; i < bodyChildren.length; i++) {
newDiv.append(bodyChildren[i]);
}
document.body.appendChild(newDiv);
}
initiate();
And i tried this as well to wrap up the body's innerHTML with a div element.
function initiate() {
var jq_script = document.createElement('script');
jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js');
document.head.appendChild(jq_script);
var div = document.createElement("div");
div.id = "wrapper";
while (document.body.firstChild) {
div.appendChild(document.body.firstChild);
}
document.body.appendChild(div);
}
initiate();
This keeps on adding the wrapper element inside body. And the above script is inside iframe.
Any solution on this?
Two problems:
It's appendChild, not append.
Once that's out of the way, though, the other problem is in your loop: childNodes is a dynamic list, and so when you move a child out of body into newDiv, the list changes, making your indexes invalid.
You can fix that by just looping, moving first child into your div, until the body runs out of children, then append the div:
var newDiv = document.createElement('div')
newDiv.id = "wrapper"; // You don't need or want setAttribute here
var bodyChildren = document.body.childNodes;
while (bodyChildren.length) {
newDiv.appendChild(bodyChildren[0]);
}
document.body.appendChild(newDiv);
Or actually, you don't even need the list, you can use firstChild:
var newDiv = document.createElement('div')
newDiv.id = "wrapper"; // You don't need or want setAttribute here
while (document.body.firstChild) {
newDiv.appendChild(document.body.firstChild);
}
document.body.appendChild(newDiv);
Within content script I use on.Message.addListener to add images with a class name to the currently active web page.
chrome.extension.onMessage.addListener(function (message, sender, sendResponse) {
// Selecting HTML tags
var divs = document.getElementsByTagName("div");
// Creating a full URL to use icon1
var imageUrl = chrome.extension.getURL("icons/icon1.png");
// Function to create an image
function PlaceImage(source_x, source_y, imageUrl) {
var newImage = document.createElement("img");
newImage.src = imageUrl;
newImage.style.position = "absolute";
newImage.style.left = source_x + 'px';
newImage.style.top = source_y + 'px';
// Assigning a class name
newImage.className = "label-key";
// Add an element to the HTML document
document.body.appendChild(newImage);
}
// Divs
for(var j=0; j<divs.length; j++) {
// Get the position of an element with getBoundingClientRect
var position = divs[j].getBoundingClientRect();
var x = position.left;
var y = position.top;
y -=32;
// Create comment image
PlaceImage(x, y, imageUrl);
}
});
Later I try to write to console by clicking on one of just created images by:
$(".label-key").click(function () {
console.log("hello");
});
There is no reaction of the browser.
I tried to write to console by accessing some class element with a different name, which was part of the original web page(received from the server). It worked fine.
More over I created another element within content script, but this time outside of onMessage.AddListener:
var newDiv = document.createElement("div");
document.body.appendChild(newDiv);
newDiv.style.width = "100px";
newDiv.style.height = "100px";
newDiv.style.backgroundColor = "red";
newDiv.className = "label-key";
It also worked fine. jQuery was able to access this element.
Therefore, I think there is something wrong with html elements created by the onMessage.addListener part of content script.
For additional reference: when I right-click on the newly created element "Inspect element" - I can see that the element is part of the html document. However, if I click "View page source" the element is not there.
Well, you are creating a new element of the class label-key, but the click handler assignment does not automagically extend to newly-created elements.
$(".label-key").click(...) is not behaving like a CSS rule despite looking like one: it collects all elements that match at the time of invocation and binds a listener for them.
So, if you add more images later, you need to add a click handler again:
function PlaceImage(source_x, source_y, imageUrl) {
var newImage = document.createElement("img");
newImage.src = imageUrl;
newImage.style.position = "absolute";
newImage.style.left = source_x + 'px';
newImage.style.top = source_y + 'px';
// Assigning a class name
newImage.className = "label-key";
newImage.click(function () {
console.log("hello");
});
// Add an element to the HTML document
document.body.appendChild(newImage);
}
im trying to dynamically create elements in the child window based on the values i have in the the parent window but no success.The child window is opening but not with the elements.Here is the code i've written,could some one please have a loot at it ? is this possible at all using javascript/jquery>
function fnOpenPrint(){
openPrint = window.open('print.htm');
childWin = openPrint.document;
var newDiv = childWin.createElement("<div id='para'>")
newDiv.innerHTML = document.forms[0].txtBranch.value;
}
try
function fnOpenPrint(){
var openPrint = window.open('print.htm');
openPrint.onload = function() {
var doc = openPrint.document;
var newDiv = doc.createElement("div");
newDiv.id = 'para';
newDiv.innerHTML = document.forms[0].txtBranch.value;
doc.body.appendChild(newDiv);
};
}
DOM manipulations in the child window must be done after it finishes loading.
createElement doesn't automatically add it to the document... you'd prbably have to do this too:
childWin.body.appendChild(newDiv);