JavaScript: DOM manipulation and after that a search over all elements - javascript

I'm going to load several new elements (via AJAX) into the DOM. After that I want to "refresh" the document variable to select existing and new elements.
I tried to simplify my question with this small example:
// Creating a new element and insert it into DOM
var newdiv = document.createElement('div');
newdiv.style.color = 'red';
newdiv.innerHTML = 'this is a new div container';
newdiv.classList = 'newdiv';
document.getElementById('existingdiv').appendChild(newdiv);
// Search the complete DOM for the new element and try to select it (but abc is null)
var abc = document.querySelector('newdiv');
abc.style.color = 'blue';
Any ideas (without jQuery)?

newdiv is a class not an element. To target that you have to specify dot (.) along with class name in the selector:
var abc = document.querySelector('.newdiv');

After that I want to "refresh" the document variable to select existing and new elements.
There's no need, document is live.
querySelector('newdiv') looks for an element with the tag name newdiv. You probably meant querySelector('.newdiv'), which looks for the first element with that class in the DOM.
Live Example:
// Creating a new element and insert it into DOM
var newdiv = document.createElement('div');
newdiv.style.color = 'red';
newdiv.innerHTML = 'this is a new div container';
newdiv.classList = 'newdiv';
document.getElementById('existingdiv').appendChild(newdiv);
// Search the complete DOM for the new element and try to select it (but abc is null)
var abc = document.querySelector('.newdiv');
abc.style.color = 'blue';
<div id="existingdiv"></div>

Related

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);

How to append a child to one of the elements in a variable by part of the class name and replace the parent?

I have a JS variable var e which is created by document.createElement method. I want to append a new element to an element inside the e which has jackson in its class name (full class name is large button 1 jackson). Also, how can I replace the large button 1 jackson element with the updated element afterwards? Would you suggest a solution?
Here is an example using querySelector
// container element
var e = document.createElement('div');
// child element with class 'large button 1 jackson'
e.innerHTML = '<div class="large button 1 jackson">some text</div>';
// insert the container element
document.body.appendChild(e);
// new element
var newElem = document.createElement('textarea');
// find a element with jackson class (using .jackson as selector)
var jackson = e.querySelector('.jackson');
// insert new element
jackson.appendChild(newElem);

document.querySelector issues

In the following code, why is document.querySelector() returning null?
var element = document.createElement('div');
element.classList.add('abc');
var test = document.querySelector("." + element.className);
You need to add a .
var test = document.querySelector("."+element.className);
EDIT
You also need to add it to body
document.body.appendChild(element);
See http://codepen.io/jammer99/pen/dMmXYL
The div is not part of the DOM until you append it to a DOM element.
You need to add a dot in front to use the querySelector on a class string: document.querySelector("."+element.className)
The DOM element you append your div to has to exist before you can access it.
window.onload=function() { // body exists
var element = document.createElement('div');
element.classList.add('abc');
var test = document.querySelector("."+element.className);
console.log(test,element.className);
document.body.appendChild(element); // NOW the DIV exists in DOM
test = document.querySelector("."+element.className);
console.log(test);
}

Changing JavaScript into jQuery - createElement

I'm trying to use the draggable and resizable jQuery function, but I may have to change a little bit of this code to jQuery.
I have this HTML code:
<div id="resizable2" class="ui-widget-content">
<h3 class="ui-widget-header">MS</h3>
</div>
This works great with the jQuery:
$(function() {
$( "#resizable" ).draggable();
$( "#resizable" ).resizable();
}
But then, I've tried to use it with a div created by javascript:
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
document.body.appendChild(newDiv);
newDiv.appendChild(h);
newDiv.className = "ui-widget-content";
h.appendChild(text);
h.className = "ui-widget-header";
newDiv.id = "resizable";
}
And it's not working
Change your dom object to a jQuery object by calling $(newdiv) and re-initialise the resizable and draggable functionality on the new content.
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
newDiv.appendChild(h);
newDiv.className = "ui-widget-content";
h.appendChild(text);
h.className = "ui-widget-header";
newDiv.id = "resizable";
$(newDiv).resizable(); //Add this
$(newDiv).draggable(); //and this
document.body.appendChild(newDiv); //Append to the dom once you've finished with it.
}
As devqon has mentioned, the reason for this is that this function adds dynamic content (content which isn't there on page load) this means that the draggable and resizable functionality is not present on this new content. This is why you need to re-initialise the connection between the new element and the functionality.
Also as menioned don't re-use ID's, they must be unique. It is bad practice to use the same id for multiple elements and will very likely lead to other issues.
Lastly, it is a good idea when creating new content to manipulate it first and add it to the page at the end. In this instance you are appending further content inside the newly created div. I would do this first and then when finished with it, add it to the page.
Hi I have changed your function to:
function addnewbox() {
var newDiv = document.createElement("div");
var h = document.createElement("h3");
var text = document.createTextNode("MS");
newDiv.id = "resizable";
newDiv.className = "ui-widget-content";
h.className = "ui-widget-header";
h.appendChild(text);
newDiv.appendChild(h);
document.body.appendChild(newDiv);
}
And I have created a jsfiddle for you to try yourself:
http://jsfiddle.net/ttw7218z/4/
Well you need to initialize resiazble plugin on new DOM elements. You already have a few JS solutions so I will post one more version using jQuery for elements creation:
function addnewbox() {
$('<div class="ui-widget-content resizable">' +
'<h3 class="ui-widget-header">MS</h3>' +
'</div>').appendTo('body').resizable();
}
One more thin you should be aware of: you should not duplicate ids, they must be unique. So instead of multiple #resizable use .resizable classes.

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