I'm trying to test if a DOM element exists, and if it does exist delete it, and if it doesn't exist create it.
var duskdawnkey = localStorage["duskdawnkey"];
var iframe = document.createElement("iframe");
var whereto = document.getElementById("debug");
var frameid = document.getElementById("injected_frame");
iframe.setAttribute("id", "injected_frame");
iframe.setAttribute("src", 'http://google.com');
iframe.setAttribute("width", "100%");
iframe.setAttribute("height", "400");
if (frameid) // check and see if iframe is already on page
{ //yes? Remove iframe
iframe.removeChild(frameid.childNodes[0]);
} else // no? Inject iframe
{
whereto.appendChild(iframe);
// add the newly created element and it's content into the DOM
my_div = document.getElementById("debug");
document.body.insertBefore(iframe, my_div);
}
Checking if it exists works, creating the element works, but deleting the element doesn't. Basically all this code does is inject an iframe into a webpage by clicking a button. What I would like to happen is if the iframe is already there to delete it. But for some reason I am failing.
removeChild should be invoked on the parent, i.e.:
parent.removeChild(child);
In your example, you should be doing something like:
if (frameid) {
frameid.parentNode.removeChild(frameid);
}
In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element) on its parent, which is to just call element.remove(). In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.
The .remove() method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.
If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode and are actually defined in the browser, and add .remove to them.
Here's the shim I came up with, which I've confirmed works in IE 8.
(function () {
var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
remove = function () {
// The check here seems pointless, since we're not adding this
// method to the prototypes of any any elements that CAN be the
// root of the DOM. However, it's required by spec (see point 1 of
// https://dom.spec.whatwg.org/#dom-childnode-remove) and would
// theoretically make a difference if somebody .apply()ed this
// method to the DOM's root node, so let's roll with it.
if (this.parentNode != null) {
this.parentNode.removeChild(this);
}
};
for (var i=0; i<typesToPatch.length; i++) {
var type = typesToPatch[i];
if (window[type] && !window[type].prototype.remove) {
window[type].prototype.remove = remove;
}
}
})();
This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.
Once you've included them shim, you'll be able to remove a DOM element element from the DOM by simply calling
element.remove();
Seems I don't have enough rep to post a comment, so another answer will have to do.
When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.
Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
for (i = a.length - 1; i >= 0; i -= 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.
And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.
Using Node.removeChild() does the job for you, simply use something like this:
var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);
In DOM 4, the remove method applied, but there is a poor browser support according to W3C:
The method node.remove() is implemented in the DOM 4 specification.
But because of poor browser support, you should not use it.
But you can use remove method if you using jQuery...
$('#left-section').remove(); //using remove method in jQuery
Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...
Related
The issue is similar to the one described here, as far as I can tell. However, I am not using mootools and my question and results are different.
This is a test page to demonstrate the issue: http://jsfiddle.net/S7rtU/2/.
I add elements to a container using createElement and appendChild. As I add each, I also store a reference to it in a private array (elems).
Then, I decide to clear the container, and do so by setting container.innerHTML = ''.
(In my example, I set it first to a pending message, and then 3s later, using setTimeout, I clear it. This is to give time to observe the changes to the DOM.)
Then, I try to repopulate the container from the elems array, calling container.appendChild for each of the stored elements.
I have tested on the browsers I have at hand: Firefox 17.0.1, Chrome 23.0.1271.97, Safari 3.1.2, IE 6 and IE 7. All except IE 6 & 7 will actually restore those elements. So they are successfully stored in memory and references not destroyed. Furthermore, the event handlers registered to those elements still work.
In IE, the elements do not reappear.
What I have read about this issue, including the other SO question, seem to suggest that references are supposed to be broken when you modify innerHTML on the container. Event handlers are also supposed to be broken. However the 3 modern browsers I tested do not break the references, nor the event handlers.
Of course, to make this work in IE I can use something like this, but this is significant extra processing if there are lots of elements:
function explicitClearContainer() {
var e;
// Explicitly remove all elements
for (var i = 0; i < elems.length; ++i) {
e = elems[i];
// Update the reference to the removed Node
elems[i] = e.parentNode.removeChild(e);
}
}
My question is what is known about this behaviour, what can be expected in different environments, what are the pitfalls of using this sort of technique?
I would appreciate any comments.
The innerHTML property was only "standardised" in HTML5, which really just documents common browser behaviour for many features. Things such as innerHTML have been implemented differently in different browsers and will continue to be different for some time, so best to avoid using it if it's causing problems.
There are other approaches to clearing the child nodes of an element, e.g.:
function removeContent(element) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
Which should avoid your issues with innerHTML and is a bit less code than your version. You can also replace element with a shallow clone of itself, but that may cause other issues.
I want to create the equivalent of an onCreate event for all tags which will be created that match a JQuery selector.
For instance, let's consider a document where the result of $("#foo > .bar > ul > li") is an empty set. I have a function called fooBar and I want this function to be called whenever a tag matching $("#foo > .bar > ul > li") was created.
I would like to define this event in my
$(function() {});
Does somebody know a possibility for this?
As far as I'm aware there aren't any events that are fired when elements are added to the DOM, so there's nothing you can bind a handler to in order to check for this.
What you can do is set up a polling routine that will periodically check the DOM for elements that match your selector, compare the current number of matches against the previous value, and perform whatever actions you wish if they differ.
var matchedElements = 0;
function poll() {
var $elements = $("#foo > .bar > ul > li");
if($elements.length > matchedElements) {
fooBar();
}
matchedElements = $elements.length;
}
setInterval(poll, 500); // runs poll() every half a second
This all assumes that you're not controlling the creation of these elements, or at least aren't controlling them in a way that allows you to reliably know they've been created.
If the only source of these elements is a single function you've written then you could simply extend that to trigger a handler for a custom event bound in jQuery.
Most practical solution
You can hook into the DOMNodeInserted event on document to detect the changes, and use .is to check if they match the selector of your choice.
$(function() {
var selector = "whatever";
$(document).on('DOMNodeInserted', function(e) {
if ($(e.srcElement || e.target).is(selector)) {
alert("Matching element inserted!");
}
});
});
See it in action.
Compatibility and alternatives
This approach is convenient, but it does have two drawbacks:
The DOMNodeInserted event is deprecated.
It does not work on IE < 9, and cannot be made to work.
As regards the first, I wouldn't consider this an issue. It may be deprecated, but as long as there is no other alternative I really don't think any browser vendor would pull this functionality. Maybe in five years or so this will become a practical issue, but since the code is 10 lines or so total it will surely be easy to update it to work with the latest standard.
For IE compatibility, the sad truth is that you cannot do anything directly. However, you can resort to verbose, horrible hacks that do provide results by modifying the prototypes of DOM elements. See an example tailored to work on IE8.
Sadly, there are multiple issues with this approach:
You need to fish out all the methods that can result in the DOM being modified (or at least, all of those you will be using) and weave them into the solution. In the future you will be obliged to check if new DOM mutation methods are added and keep up with supporting them.
You need to be extra careful to provide correct replacements for the methods, for all browsers that you choose to target with this (if more than one).
Extending the DOM (in general) can be problematic. If you thought this specific method of extension is bad, consider that IE7 does not support it and on that browser you 'd have to replace methods on all elements in the DOM to make sure you hook into every possible modification.
Specifically, you cannot target all current browsers with just this code (e.g. Chrome defines these methods on Node.prototype, not on Element.prototype). Targeting future browsers should not be mentioned even if joking.
Finally, you can always decide to use polling to detect changes, as Anthony explains in his answer.
Related resources
DOMNodeInserted equivalent in IE?
Modify prototypes of every possible DOM element
So I realize that in no way do I want to do:
Element.protoype.myfunc = function () {}
But, is this the same or not and is this a good practice?
var e = document.querySelector(q);
e.html = function (html) {
this.innerHTML = html;
}
e.html("Am I in trouble?");
Extending Element will not work in all browsers (notably IE<8). See also this SO question
Extending single elements may result in memory leaks: if such elements are deleted, the method can still exist, containing a link to the non existent element. See this link (it's about handler methods, but it can also apply to extension methods afaik).
In my JSP/HTML I have this:
<div id="exampleLabel"> </div>
Then in my javascript section I have a function called from an onclick like this;
function changeLabel(){
exampleLabel.firstChild.nodeValue = 'LABEL HAS CHANGED';
}
This works fine in Chrome, does nothing in Firefox and in IE an error on page appears saying
exampleLabel.firstChild is null or not an object.
Ok I can take it that there was no firstChild so trying to do firstChild.ANYTHING would be a NPE, I can even take it that the other browsers don't just initialize it themselves like Chrome obviously does.
Question is, how do I initialize it myself so I can then go .nodeValue = "blahblah" on it?
The reason it doesn't work in IE is that unlike all other major browsers, it doesn't create text nodes for whitespace in your HTML, hence your <div> that only contains a space has no child nodes in IE. I would suggest adding a text node manually, or changing an existing one.
Also, unless you've declared exampleLabel elsewhere, you're relying on a non-standard and rather icky feature of IE and Chrome that maps IDs of DOM elements to properties of the global object (i.e., you can refer to an element as a variable by its ID). This doesn't work in other browsers. What you should do instead is use document.getElementById().
function changeLabel(labelText) {
var exampleLabel = document.getElementById('exampleLabel');
var child = exampleLabel.firstChild;
if (!child) {
child = document.createTextNode('');
exampleLabel.appendChild(child);
}
child.nodeValue = labelText;
}
changeLabel('LABEL HAS CHANGED');
Create a textNode and then append it.
function changeLabel(){
var textNode = exampleLabel.firstChild;
if (!textNode) {
textNode = document.createTextNode('foo');
exampleLabel.appendChild(textNode);
}
textNode.nodeValue = 'LABEL HAS CHANGED';
}
The native document.createElement() is silly-stupid (it takes only a tag name and no attributes). How come I can't override it? How come this doesn't work?
var originalFunction = document.createElement;
document.createElement = function(tag, attributes) {
var element = originalFunction(tag);
if (attributes) {
for (var attribute in attributes) {
element.setAttribute(attribute, attributes[attribute]);
}
}
return element;
};
The problem is that browsers blow up when you try to replace a native function. Since document is not a JavaScript primitive, you can't create a prototype for it either. WTF.
As far as I can tell the problem is that a call to the document.createElement() function even when referenced has to be from the document. So modify your code:
var element = originalFunction.call(document, tag);
FWIW (informational): you can override "native" methods, in some cases, and in some browsers at least. Firefox lets me do this:
document.createElement = function(f) { alert(f); };
Which then does as you expect when invoked. But your whole block of code above throws an error, at least via Firebug.
Philosophically, you should be able to do this. You can certainly, say, redefine methods on the Array object, etc. But the window (DOM) methods are not covered by ECMAScript, and so they're probably allowed to be implementation-dependent. And of course, they are this way for security reasons.
Why not just use the method in your own function- write it the way you want, and never write document.createElement again....
document.create= function(tag, parent, attributes){
tag= document.createElement(tag);
for(var p in attributes){
if(p== 'css') tag.style.cssText= attributes.css;
else if(p== 'text') tag.appendChild(document.createTextNode(attributes.text));
else tag[p]= attributes[p];
}
if(parent) parent.appendChild(tag);
return tag;
}
document.create('p',document.body,{css:'font-style:italic',className:'important',title:'title',
text:'whatever text you like'});
As far as I know you cannot override native methods for security reasons. For non-native methods it's no problem at all.
There's no way to override that, however you can do some hack around if you not affraid of passing non conventional parameter(s) to a native function. So the thing about createElement that its ment to be the part of the XML DOM, thus you can create whatever tagname you want. And here is the trick, if you pass your attributes as a part of the first parameter (the tagname), separating them with the delimiters of your choise, and then listening to the onchange event of the DOM and if your delimiters are presented in any tag, replace them with the proper markup, using RegExp for example.
The proxy pattern mentioned at JavaScript: Overriding alert() should work for this.
It's mentioned in jquery docs but doesn't look like it actually has a dependency on jQuery.
More info here: http://docs.jquery.com/Types#Proxy%5FPattern
Try this.
document.constructor.prototype.createElement = _ => `P for "pwned"`;
console.log(document.createElement("P"));