I wonder if there's any way to get the JS code of an existing HTML element using any existing method. I am trying to print the code generator of any DOM element, so when the user clicks on any HTML element of the webpage, a message will be shown with the source code to create that element in Javascript.
For example, I have a Div created:
var div = document.createElement("div");
div.style.border = "1px dotted red";
div.onmouseover=function(){div.style.color = "red"};
div.innerHTML = "I'm the div";
And then I was trying to obtain the source code, but:
document.body.appendChild(div.innerHTML);
This option only writes the textual content: "I'm the div". SO I tryed:
document.body.appendChild(div.outerHTML);
But it writes the HTML code without the onmouseover function: "I'm the div"
What I really need is to show this code (or something similar):
var div = document.createElement("div");
div.style.border = "1px dotted red";
div.onmouseover=function(){div.style.color = "red"};
div.innerHTML = "I'm the div";
http://jsfiddle.net/x2zJs/
Do you have any idea where can I start reading?
Thanks a lot,
outerHTML
outerHTML is a good choice with several limitations:
today (2014) you can't get attached listeners natively
outerHTML uses html node serialization, which uses uses xml attributes serialization algorithm
In other words, IDL attributes are ignored, only content attributes are serialized.
Events by IDL attributes are coded as
div.onmouseover=function(){div.style.color = "red"};
div.addEventListener("mouseover",function() {div.style.backgroundColor="blue";});
See more about events
Whereas events by content attributes are coded as
div.setAttribute("onmouseover","this.style.color='red'");
Using content attribute, the outerHTML looks like this:
<div onmouseover="this.style.color='red'" style="border: 1px dotted red;">
I'm the div
</div>
See your updated fiddle.
Long story short, there are two ways to code a handler:
var setColor = function(e) { e.target.style.color = "red"; }
div.onmouseover = setColor; // IDL, not seen by outerHTML
div.setAttribute("onmouseover","setColor(event)"); // content, seen by outerHTML
eventListenerList
If you want to retrieve the IDL events somehow, nice proposed eventListenerList property was removed from DOM3 spec proposal (see here).
If you want to write a firefox addon (something like code inspector), extending the Element.prototype will do the trick (as I tested, it works in Firefox, Chrome and Opera, it doesn't work in IE7):
(function() {
Element.prototype.eventListenerList = {};
Element.prototype._addEventListener = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(a,b,c) {
this._addEventListener(a,b,c);
if(!this.eventListenerList[a]) this.eventListenerList[a] = [];
this.eventListenerList[a].push(b);
};
})();
To be precise, you should also override the Element.prototype.removeEventListener to remove the event from the custom EventListenerList.
Now you can add the events by addEventListener as usual:
function handlerA() { alert('a'); }
function handlerB() { alert('b'); }
function handlerC() { alert('c'); }
// attach handlers
div.onclick = handlerC;
div.addEventListener("click",handlerA);
div.addEventListener("click",handlerB);
...and to display the code of the listeners. I will do this for onclick event, in your code you should iterate through every possible event. Don't forget the eventual onclick listener (you can't override Element.prototype.onclick because it is non-configurable property):
var clickListeners = "";
if(div.eventListenerList.click)
div.eventListenerList.click.forEach(function(f) {
clickListeners+= f.toString();
});
if(div.onclick) clickListeners+= div.onclick.toString();
alert(clickListeners);
See and test the fiddle. Put these pieces together as it suits to your addon.
There is nothing built-in that will give you what you want, try the "aardvark bookmarklet" it has a somewhat nice js generating command.
http://karmatics.com/aardvark/bookmarklet.html
Well, you could wrap the creation of your div element with a function and then parse and print contents of that function.
Following is a working example (tested in Chrome, Firefox and Safari):
Also here http://jsfiddle.net/smnh/x2zJs/2/
function createDiv() {
var div = document.createElement("div");
div.style.border = "1px dotted red";
div.onmouseover = function() {div.style.color = "red"};
div.innerHTML = "I'm the div";
div.creationString = getFunctionContnet(createDiv); // noprint
return div; // noprint
}
function getFunctionContnet(func) {
var regExp = /function[^(]*\([^)]*\)[^{]*{(?:\s*\n)?(\s*)([\s\S]*)(?:\n\s*)}/,
match,
indention, indentionRE,
noprintRE = /\/\/.*noprint.*/,
content = null,
lines, i;
match = regExp.exec(func.toString());
if (match !== null) {
indention = match[1];
content = match[2];
lines = content.split("\n");
// if first line of the function is indented,
// remove that indention from all function lines.
if (typeof indention !== "undefined") {
indentionRE = new RegExp("^" + indention);
for (i = 0; i < lines.length; i++) {
if (indentionRE.test(lines[i])) {
lines[i] = lines[i].substr(indention.length);
}
}
}
// don't print lines with "// noprint"
for (i = lines.length - 1; i >= 0; i--) {
if (noprintRE.test(lines[i])) {
lines.splice(i, 1);
}
}
content = lines.join("\n");
}
return content;
}
Here if you create your div and log the creationString you will get the text of the function.
div = createDiv();
console.log(div.creationString);
If you have control over the creation of the elements you could ensure that each element is created in it's own separate function. Then a simple function can get the function body.
function createElement1() {
var div = document.createElement("div");
div.style.border = "1px dotted red";
div.onmouseover=function(){div.style.color = "red"};
div.innerHTML = "I'm the div";
}
function getFunctionBody(func) {
var functionText = func.toString();
return functionText.slice(functionText.indexOf("{") + 1, functionText.lastIndexOf("}"));
}
Here's a working example. http://jsfiddle.net/C5b7n/
Related
I created different elements-paragraphs with createElement()/createTextNode() and added them to the body.
My problem is that i want to make those divs links or be able to add events such as onclick and obviously there is no HTML code to do that..just javascript generated objects.
my code atm:
for (i=0; i<10; i++){
var newDiv = document.createElement("div");
newDiv.className = "block";
var heading = document.createElement("h2");
var newContent = document.createTextNode(data[1][i]);
heading.className="title";
heading.appendChild(newContent);
newDiv.appendChild(heading);
var paragraph = document.createElement("p");
var newContent2 = document.createTextNode(data[2][i]);
paragraph.className="light";
paragraph.appendChild(newContent2);
newDiv.appendChild(paragraph);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
You can add the event listener to the object you just created. The object does not have to be HTML. Read more about adding event listeners and see simple example:
var someDiv = document.createElement('div');
var txt = document.createTextNode('click me');
someDiv.append(txt);
document.body.append(someDiv);
var myFancyFunction = function() {
alert('you clicked me');
};
someDiv.addEventListener('click', myFancyFunction);
Update after your code you can add an event listener to those objects you create on the fly. You can also add different functions on the same event. In this case it's the same function for both elements/objects .. play with this: (I changed the data to "dummy data" as there was no data)
var myClick = function(event) {
alert(event.target.innerHTML);
};
for (i=0; i<10; i++){
var newDiv = document.createElement("div");
newDiv.className = "block";
var heading = document.createElement("h2");
var newContent = document.createTextNode('dummy data1 index: ' + i);
heading.className="title";
heading.appendChild(newContent);
newDiv.appendChild(heading);
var paragraph = document.createElement("p");
var newContent2 = document.createTextNode('dummy data2 index: ' + i);
paragraph.className="light";
paragraph.appendChild(newContent2);
newDiv.appendChild(paragraph);
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
heading.addEventListener('click', myClick);
paragraph.addEventListener('click', myClick);
}
You can simply call addEventListener on the JS-generated objects, even before they are inserted into the DOM, or are never inserted at all:
let div = document.createElement('div');
div.addEventListener('click', function(event) {
// do something
});
// This will trigger a call of the registered click callback,
// regardless of whether the div is in the DOM:
div.dispatchEvent(new Event('click', {
"bubbles": true,
"cancelable": false,
}));
// To add it to the DOM, simply add it the way you wish:
document.body.appendChild(div);
EventTarget.dispatchEvent allows you to trigger an event in a computational way (has equivalent effect to actually clicking the div)
Do take note of the browser compatibility of the event constructor in the example above.
Once an element is added to the dom, you can select it just like any other element.
// Create the element
var paragraph = document.createElement('p');
// Give it an `id`
paragraph.id = 'foo';
// Add the element to the `dom`
document.body.appendChild(paragraph);
// Add the listener
paragraph.addEventListener('click', function() {
this.innerHTML = 'It was clicked';
});
p {
height:20px;
padding:10px;
outline:1px solid #bada55;
}
In the example above, I added an id. If for some reason you need to re-select the element it may make it easier.
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);
I want to know if we can change tag name in a tag rather than its content. i have this content
< wns id="93" onclick="wish(id)">...< /wns>
in wish function i want to change it to
< lmn id="93" onclick="wish(id)">...< /lmn>
i tried this way
document.getElementById("99").innerHTML =document.getElementById("99").replace(/wns/g,"lmn")
but it doesnot work.
plz note that i just want to alter that specific tag with specific id rather than every wns tag..
Thank you.
You can't change the tag name of an existing DOM element; instead, you have to create a replacement and then insert it where the element was.
The basics of this are to move the child nodes into the replacement and similarly to copy the attributes. So for instance:
var wns = document.getElementById("93");
var lmn = document.createElement("lmn");
var index;
// Copy the children
while (wns.firstChild) {
lmn.appendChild(wns.firstChild); // *Moves* the child
}
// Copy the attributes
for (index = wns.attributes.length - 1; index >= 0; --index) {
lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
}
// Replace it
wns.parentNode.replaceChild(lmn, wns);
Live Example: (I used div and p rather than wns and lmn, and styled them via a stylesheet with borders so you can see the change)
document.getElementById("theSpan").addEventListener("click", function() {
alert("Span clicked");
}, false);
document.getElementById("theButton").addEventListener("click", function() {
var wns = document.getElementById("target");
var lmn = document.createElement("p");
var index;
// Copy the children
while (wns.firstChild) {
lmn.appendChild(wns.firstChild); // *Moves* the child
}
// Copy the attributes
for (index = wns.attributes.length - 1; index >= 0; --index) {
lmn.attributes.setNamedItem(wns.attributes[index].cloneNode());
}
// Insert it
wns.parentNode.replaceChild(lmn, wns);
}, false);
div {
border: 1px solid green;
}
p {
border: 1px solid blue;
}
<div id="target" foo="bar" onclick="alert('hi there')">
Content before
<span id="theSpan">span in the middle</span>
Content after
</div>
<input type="button" id="theButton" value="Click Me">
See this gist for a reusable function.
Side note: I would avoid using id values that are all digits. Although they're valid in HTML (as of HTML5), they're invalid in CSS and thus you can't style those elements, or use libraries like jQuery that use CSS selectors to interact with them.
var element = document.getElementById("93");
element.outerHTML = element.outerHTML.replace(/wns/g,"lmn");
FIDDLE
There are several problems with your code:
HTML element IDs must start with an alphabetic character.
document.getElementById("99").replace(/wns/g,"lmn") is effectively running a replace command on an element. Replace is a string method so this causes an error.
You're trying to assign this result to document.getElementById("99").innerHTML, which is the HTML inside the element (the tags, attributes and all are part of the outerHTML).
You can't change an element's tagname dynamically, since it fundamentally changes it's nature. Imagine changing a textarea to a select… There are so many attributes that are exclusive to one, illegal in the other: the system cannot work!
What you can do though, is create a new element, and give it all the properties of the old element, then replace it:
<wns id="e93" onclick="wish(id)">
...
</wns>
Using the following script:
// Grab the original element
var original = document.getElementById('e93');
// Create a replacement tag of the desired type
var replacement = document.createElement('lmn');
// Grab all of the original's attributes, and pass them to the replacement
for(var i = 0, l = original.attributes.length; i < l; ++i){
var nodeName = original.attributes.item(i).nodeName;
var nodeValue = original.attributes.item(i).nodeValue;
replacement.setAttribute(nodeName, nodeValue);
}
// Persist contents
replacement.innerHTML = original.innerHTML;
// Switch!
original.parentNode.replaceChild(replacement, original);
Demo here: http://jsfiddle.net/barney/kDjuf/
You can replace the whole tag using jQuery
var element = $('#99');
element.replaceWith($(`<lmn id="${element.attr('id')}">${element.html()}</lmn>`));
[...document.querySelectorAll('.example')].forEach(div => {
div.outerHTML =
div.outerHTML
.replace(/<div/g, '<span')
.replace(/<\/div>/g, '</span>')
})
<div class="example">Hello,</div>
<div class="example">world!</div>
You can achieve this by using JavaScript or jQuery.
We can delete the DOM Element(tag in this case) and recreate using .html or .append menthods in jQuery.
$("#div-name").html("<mytag>Content here</mytag>");
OR
$("<mytag>Content here</mytag>").appendTo("#div-name");
I have a div with id, which has some other div's without id.
Some thing like:
<div class="mainDivClass" id="mainDiv">
<div class="subDivClass">
<h2>one</h2>
Hello One!!
</div>
<div class="subDivClass">
<h2>two</h2>
Hello Two!!
</div>
<div class="subDivClass">
<h2>three</h2>
Hello Three!!
</div>
</div>
In my javascript, I am looping through above div like:
var divLists = document.getElementById('mainDiv').firstChild.childNodes;
for (var i = 0; i < tabLists.length; i++) {
var anchor = divLists[i].firstChild;
var iconFile;
if(i==0)
{
iconFile = 'details.png';
}
else
{
iconFile = 'search1.png';
}
anchor.style.backgroundImage = 'url(' + iconFile + ')';
anchor.style.backgroundRepeat = 'no-repeat';
anchor.style.backgroundPosition = '1px 2px';
anchor.className = 'toplevel-tab';
}
As shown, I am setting iconFile variable on value of i. So for i = 0, it would be details.png while for all others, it would be search1.png.
Now, I want to decide the iconFile variable value based on the h2 value of the element.
That is, if h2 is banana, banana.png will go in iconFile but if h2 is orange, orange.png will be selected.
How to get h2 value inside javascript ?
Thanks for reading!!
Nik
Don't use innerHTML, it's an unreliable proprietary Microsoft method; should you get used to using it you will immediately begin having problems if you start coding at an application level and not be able to figure out why. Stick to using DOM specifications instead.
An example that you can obviously throw in to a loop...
document.getElementById('subDivClass').getElementsByTagName('h2').firstChild.nodeValue
.parentNode - The parent element of the currently referenced element.
.parentNode.parentNode.parentNode - You can use this as much as you want to go up or around the DOM.
.childNodes[0] - Index of child elements, does NOT contain reference to text nodes AFTER an element (use treewalker for that).
.nodeValue - The text value of a node, do NOT use innerHTML.
.textContent - Gets or sets the text of an element (but no child elements); a bit easier than nodeValue though it still has reasonable limitations.
.previousSibling - The element BEFORE the reference element, not a child/parent.
.nextSibling - The element AFTER the reference element, not a child/parent.
You can reveal all objects (e.g. methods, properties and other objects) for any object using the in operator to discover what else is available to you...
for (i in document.getElementById('mainDiv')) {alert('i = '+i);}
It should be noted that if you're stuck using the HTML parser .nodeName will be all uppercase (e.g. the old Internet Explorer way) versus using the XML parser (application/xhtml+xml) the .nodeName will properly return the element's name as lowercase (unless you're really in to the 90's style or something).
It should also be noted that when you use previousSibling and nextSibling that line breaks alone will create a textNode and those line breaks will mess with CSS (setting the font-size to 5px will generally eliminate this).
If you want all the H2 elements inside the mainDivClass you can use the getElementsByTagName method:
var outerDiv = document.getElementById("mainDiv");
var h2s = outerDiv.getElementsByTagName("h2");
This returns all the H2 elements as an array of elements.
var answer = function () {
var parent = document.getElementById("mainDiv"),
h2 = parent.getElementsByTagName("h2"),
a = h2.length,
b;
for (b = 0; b < a; b += 1) {
switch (h2[b].innerHTML) {
case "one":
//do something
break;
case "two":
//do something
break;
default:
//do something else
break;
}
}
};
The h2 value will be used as below:
for (var i = 0; i < tabLists.length; i++) {
var anchor = tabLists[i].firstChild;
var iconFile;
if(tabLists[i].firstChild.innerHTML == "Tab 0")
{
iconFile = 'one.png';
}
else if(tabLists[i].firstChild.innerHTML == "apple")
{
iconFile = 'apple.png';
}
else if(tabLists[i].firstChild.innerHTML == "orange")
{
iconFile = 'banana.png';
}
else if(tabLists[i].firstChild.innerHTML == "banana")
{
iconFile = 'orange.png';
}
anchor.style.backgroundImage = 'url(' + iconFile + ')';
anchor.style.backgroundRepeat = 'no-repeat';
anchor.style.backgroundPosition = '1px 2px';
anchor.className = 'toplevel-tab';
}
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);