Div inside a new div with appendchild - javascript

I have this function that create a new div with a class name.
Now I want to add a new div inside the created div. But nothing happened. When I look in the console with Chrome, nothing gets rendered inside the new div...
Any ideas?
function diceWrapper(){
var wrappId=document.createElement("div");
document.getElementById("page-content-wrapper").appendChild(wrappId);
document.getElementsByTagName("div")[3].setAttribute("class", "dice-window-wrapper");
}
function menubar(){
var menuid=document.createElement("div");
document.getElementById("dice-window-wrapper").appendChild(menuid);
document.getElementsByTagName("div")[4].setAttribute("class", "dice-menubar-wrapper");
}
And while I'm already asking, the new created <div class="dice-window-wrapper".
Keeps pushing down some other elements that are suposed to be before this div class. Even when the attributes are [0] and [1].

It seems like you're trying to find the newly created <div> and then modify it. It would be better to make all modifications first and only then add it to the document.
function createElementWithClass(elementName, className)
{
var el = document.createElement(elementName);
el.className = className;
return el;
}
var outerDiv = createElementWithClass('div', 'dice-window-wrapper'),
innerDiv = createElementWithClass('div', 'dice-menubar-wrapper');
outerDiv.appendChild(innerDiv);
document
.getElementById("page-content-wrapper")
.appendChild(outerDiv);

Related

Add element to a div with javascript

I want to add an element (child, div) to a mother-div, that already has one or more children. I made a script for this action but when I execute the script I am not able to manipulate style attributes afterwards. So I assume I did something wrong in my creation-script. I also added a console message (end of the script) and that also indicates there are no style attributes filled in at the new div. So, please could someone indicate what the reason is...
As I am quite new to javascript I assume the reason is quite simple. But although I checked many other questions and solutions, I do not get the proper solution for my issue. I think it should be in appendChild or insertBefore.
function preparevideo(videonaam, titel) {
// add a div to the video-div
const nieuwetitel = document.createElement("div");
// give the new div an id so it will be unique
nieuwetitel.id = videonaam + '-id';
// give the div a class for the markup
nieuwetitel.className = 'page-roel-video-titel';
// create the text in the div
const textnode = document.createTextNode(titel);
// add the textnode to the div
nieuwetitel.appendChild(textnode);
// find the element where the new div should be added to
let videomodule = document.getElementById(videonaam);
// and finally add the new div to the video-div, as the first child
videomodule.insertBefore(nieuwetitel, videomodule.children[0]);
console.log('-------after adding div------');
console.log('-------complete style of titleblock------');
console.log(document.getElementById(videonaam + '-id').style);
console.log('prepare video afgerond');
}
preparevideo("naam1","Eerste video");
<div id="naam1"></div>
As you didn't set any style attribute before console.log that's why you didn't get any result. After implementing some style, you can log the the style. Then you will see the difference.
Here I added some style before the console.log
function preparevideo(videonaam, titel) {
// add a div to the video-div
const nieuwetitel = document.createElement("div");
// give the new div an id so it will be unique
nieuwetitel.id = videonaam + '-id';
// give the div a class for the markup
nieuwetitel.className = 'page-roel-video-titel';
// create the text in the div
const textnode = document.createTextNode(titel);
// add the textnode to the div
nieuwetitel.appendChild(textnode);
// find the element where the new div should be added to
let videomodule = document.getElementById(videonaam);
// and finally add the new div to the video-div, as the first child
videomodule.insertBefore(nieuwetitel, videomodule.children[0]);
// Applying style
document.getElementById(videonaam + '-id').style.backgroundColor = 'red';
document.getElementById(videonaam + '-id').style.color = 'white'
console.log('-------after adding div------');
console.log('-------complete style of titleblock------');
console.log(document.getElementById(videonaam + '-id').style);
console.log('prepare video afgerond');
}
preparevideo("naam1","Eerste video");
<div id="naam1"></div>
You already gave it a class, you can target it in your css and added the needed styles
The problem is that there is no unique id value for nieuwetitel element generated. When you use getElementById() method you get only first element from DOM.

innerHTML is not working inside a function

I'm a beginner in Javascript programming. innerHTML method is not working in a function to update content of a HTML element.
My JS code is :
$(':button').on("click", function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
var sliceId = buttonElementId.charAt(buttonElementId.length - 1);
bringData(sliceId);
})
function bringData(id) {
var a = localStorage.getItem("Blogs")
var b = JSON.parse(a)
console.log(b[id].blogHeader)
document.getElementById("foo").innerHTML = b[id].blogHeader
}
Buttons and element which has id of "foo" are at different HTML pages. I want to update content of that element after clicking any button from other page, but it is not working. The content still remains same. What is my mistake ?
Note : If I use innerHTML property out of a function, it works and content is changing.

How do we convert jQuery prepend() to VanillaJS [duplicate]

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'beforebegin'
Before the element itself.
'afterbegin'
Just inside the element, before its first child.
'beforeend'
Just inside the element, after its last child.
'afterend'
After the element itself.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

JavaScript removeChild does not remove div element

I am facing a problem with JavaScript removeChild function and unfortunately its the first time I can't find what's wrong on the forum. Here is the scenario:
-Create div elements with a for loop and put the word test in it
-When one of those div is clicked, append to it the div element stored in a Foo object
-If the div from Foo object is clicked, remove it from DOM
Here is the code I use. Tried in IE and FF. No error is displayed, removeChild SEEMS to work ok, BUT the foo div is never removed. Hopefully someone can help me find out why that doesn't work.
function Foo() {
this.container = document.createElement("div");
this.container.appendChild(document.createTextNode("foo"));
this.container.onclick = function() {
// in the function'this' refers to the clicked element, i.e. container
console.log(this.parentNode); // the clicked div has a parent
console.log(this.parentNode.removeChild(this)); // the div is removed from DOM
console.log(this.parentNode); // null, the clicked div has no more parent but...
// foo is STILL DISPLAYED ?!
}
}
var foo = new Foo();
function Test() {
// create 3 div with the word test inside
for(i=0; i<3; i++) {
var t = document.body.appendChild(document.createElement("div"));
t.appendChild(document.createTextNode("test"));
// when test div is clicked, append to it the container (a div element) from object foo
// due to the for loop we need a closure for t
t.onclick = function(t){ return function() {
t.appendChild(foo.container); // here it works great and t is moved to the clicked test div
}; }(t);
}
}
new Test();
Many thanks for taking the time to investigate my issue
When you click the container with the word foo in it, you also click the t div with the word test in it. Which has a click handler that does append your foo.container back to the element from which your foo.container.onclick handler has just removed it.
Quick fix: After the container has handled the click event, it stops propagation of the event to elements higher in the DOM tree:
…
this.container.onclick = function(e) {
// in the function'this' refers to the clicked element, i.e. container
console.log(this.parentNode); // the clicked div has a parent
console.log(this.parentNode.removeChild(this)); // the div is removed from DOM
console.log(this.parentNode); // null, the clicked div has no more parent
e.stopPropagation();
// foo is NO MORE DISPLAYED
}
…
Advanced fix: Don't attach the handler that adds foo to the t element, but only to the test word. You will need an extra element for that, though:
…
var t = document.body.appendChild(document.createElement("div"));
var s = t.appendChild(document.createElement("span"));
s.appendChild(document.createTextNode("test"));
// when test div is clicked, append to it the container (a div element) from object foo
// due to the for loop we need a closure for t
s.onclick = function(s){ return function() {
s.appendChild(foo.container); // here it works great and t is moved to the clicked test div
}; }(s);
…
A variant of this would be to not append the foo.container to t itself, but as a sibling or so.
you added onclick event to the container, so the correct code would be:
function Foo() {
this.container = document.createElement("div");
this.container.appendChild(document.createTextNode("foofoofoooooo"));
this.container.onclick = function() {
this.removeChild(this.firstChild);
}
}
var foo = new Foo();
function Test() {
// create 3 div with the word test inside
for(i=0; i<3; i++) {
var t = document.body.appendChild(document.createElement("div"));
t.appendChild(document.createTextNode("test"));
// when test div is clicked, append to it the container (a div element) from object foo
// due to the for loop we need a closure for t
t.onclick = function(t){ return function() {
t.appendChild(foo.container); // here it works great and t is moved to the clicked test div
}; }(t);
}
}
new Test();
I tested and it works!

How can I implement prepend and append with regular JavaScript?

How can I implement prepend and append with regular JavaScript without using jQuery?
Here's a snippet to get you going:
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.
Perhaps you're asking about the DOM methods appendChild and insertBefore.
parentNode.insertBefore(newChild, refChild)
Inserts the node newChild as a child of parentNode before the
existing child node refChild. (Returns newChild.)
If refChild is null, newChild is added at the end of the list of
children. Equivalently, and more readably, use
parentNode.appendChild(newChild).
You didn't give us much to go on here, but I think you're just asking how to add content to the beginning or end of an element?
If so here's how you can do it pretty easily:
//get the target div you want to append/prepend to
var someDiv = document.getElementById("targetDiv");
//append text
someDiv.innerHTML += "Add this text to the end";
//prepend text
someDiv.innerHTML = "Add this text to the beginning" + someDiv.innerHTML;
Pretty easy.
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML, with appropriate first argument:
'beforebegin'
Before the element itself.
'afterbegin'
Just inside the element, before its first child.
'beforeend'
Just inside the element, after its last child.
'afterend'
After the element itself.
Hint: you can always call Element.outerHTML to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
DEMO
Caution: insertAdjacentHTML does not preserve listeners that where attached with .addEventLisntener.
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`Hello World`);
document.body.appendHtml(`Hello World`);
Here's an example of using prepend to add a paragraph to the document.
var element = document.createElement("p");
var text = document.createTextNode("Example text");
element.appendChild(text);
document.body.prepend(element);
result:
<p>Example text</p>
In order to simplify your life you can extend the HTMLElement object. It might not work for older browsers, but definitely makes your life easier:
HTMLElement = typeof(HTMLElement) != 'undefined' ? HTMLElement : Element;
HTMLElement.prototype.prepend = function(element) {
if (this.firstChild) {
return this.insertBefore(element, this.firstChild);
} else {
return this.appendChild(element);
}
};
So next time you can do this:
document.getElementById('container').prepend(document.getElementById('block'));
// or
var element = document.getElementById('anotherElement');
document.body.prepend(div);
In 2017 I know for Edge 15 and IE 12, the prepend method isn't included as a property for Div elements, but if anyone needs a quick reference to polyfill a function I made this:
HTMLDivElement.prototype.prepend = (node, ele)=>{
try { node.insertBefore(ele ,node.children[0]);}
catch (e){ throw new Error(e.toString()) } }
Simple arrow function that's compatible with most modern browsers.
var insertedElement = parentElement.insertBefore(newElement, referenceElement);
If referenceElement is null, or undefined, newElement is inserted at the end of the list of child nodes.
insertedElement The node being inserted, that is newElement
parentElement The parent of the newly inserted node.
newElement The node to insert.
referenceElement The node before which newElement is inserted.
Examples can be found here: Node.insertBefore
You can also use unshift() to prepend to a list
document.write() is not a good practice, some browsers like Chrome give you a warning if you use it, and it may be a bad solution if you are providing it to a customer, they don't want to use your code and see warnings in the debug console!
Also jQuery may also be a bad thing if you are giving your code to a customer who already uses jQuery for other functionality on their site, there will be a conflict if there is already a different version of jQuery running.
If you want to insert content into an iframe, and do that with pure JS, and with no JQuery, and without document.write(), I have a solution.
You can use the following steps
1.Select your iframe:
var iframe = document.getElementById("adblock_iframe");
2.Create an element that you want to insert into the frame, let's say an image:
var img = document.createElement('img');
img.src = "https://server-name.com/upload/adblock" + id + ".jpg";
img.style.paddingLeft = "450px";
//scale down the image is we have a high resolution screen on the client side
if (retina_test_media == true && high_res_test == true) {
img.style.width = "200px";
img.style.height = "50px";
} else {
img.style.width = "400px";
img.style.height = "100px";
}
img.id = "image";
3.Insert the image element into the iframe:
iframe.contentWindow.document.body.appendChild(img);
This is not best way to do it but if anyone wants to insert an element before everything, here is a way.
var newElement = document.createElement("div");
var element = document.getElementById("targetelement");
element.innerHTML = '<div style="display:none !important;"></div>' + element.innerHTML;
var referanceElement = element.children[0];
element.insertBefore(newElement,referanceElement);
element.removeChild(referanceElement);

Categories

Resources