DOM manipulation - Why removeChild() method instead of remove()? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does removeChild need a parent node?
Cross-browsers way to remove a node element is to use removeChild() method.
However, this way expects us to precise the node's parent as follows:
myNodeToRemove.parentNode.removeChild(myNodeToRemove);
Why didn't browsers implement the remove method with a more object-oriented way like this:
myNodeToRemove.remove();
With remove() method starting as follows:
function remove(){
var parentNode = this.parentNode;
....
}
Indeed, using this way, no need to manually get the node's parent.

For the question:
Why didn't browsers implement the remove method with a more object-oriented way like this
myNodeToRemove.remove();
...you need to study Javascript history, how the language was born, how APIs were born and so on. Then you understand how we ended up with the clusterfuck called modern web. The history is hilarious.
Good place to start is to watch Crockford on Javascript videos
http://javascript.crockford.com/#video
Also regarding function naming and object-oriented practices this is a good video:
http://vimeo.com/43380467

I think the reason to use the combination of parentNode and removeChild ensures that we are referencing the removeChild method on the actual parent of the container that we wish to remove.

Related

Backbone - What is the more efficient scoped finding method for a DOM element?

I'm aware there are many ways you can do a DOM query inside a view:
$(view.el).find("#element");
$(“#element”, view.el);
view.$("#element");
Which one is the best way to go, and why?
Bakcbone keeps a reference to the the el of the view, so the last one will be the shorthand version of view.$el.find('#element');
view.$("#element"); /// is like I said is just the same that :
view.$el.find('#element');
I think this means the last one is the fastest as its only looking into the el and not in the entire DOM and still uses find.
take a look at this link. http://pivotallabs.com/shorthand-for-searching-a-view-s-dom-in-backbone/
Always use find over context selector.
" It’s true, where possible you should always try to run your selections based on a context however it’s useful just to bare in mind that when you’re passing a context to the jQuery constructor, it creates an extra unnecessary extra function call.
jQuery’s insides run content.find(selector) anyway, so you can technically skip that step if you’re working in a page structure that may not benefit greatly from using context. Below you can see an example of what I’m talking about. "
Source : 8 jQuery Performance & Optimization Tips You Need In 2010 (Tip #6)
Yes the article is old, but it is still true.
TL;DR version : Context selector call the .find() function. Using .find() directly reduce the number of call.

Is getElementById optional in some browsers? [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 8 years ago.
When accessing elements by window.someThing, the "someThing" should be the name of html element. But what I see now, is that I can access an element by id in the same way, without document.getElementById. When has this been changed? It looks like it works in Chrome, IE, Firefox 13, but not in Firefox 12.
For example:
<div id="MyDiv">Content</div>
<script>
MyDiv.innerHTML = "New Content";
</script>
Why does the example above work? Why don't I have to do:
var MyDiv = document.getElementById('MyDiv');
Is it something new, or has it always been possible and I just didn't know it?
http://www.quirksmode.org/dom/w3c_core.html#gettingelements
It's been (mostly) implemented since IE 5.5
I can't really find any info on using the ID as variable name. I'd suggest on sticking to getElementById("MyDiv").doSomething instead of MyDiv.doSomething, to improve compatibility.
Especially when you're writing larger scripts, you may mix up variable names with id's used in the page. getElementById ensures you "get" the DOM element.
This is not standard behavior in JavaScript. When adding a variable as you did with var MyDiv, the variable was added to the window object so that it could be accessed directly as if it were a property, but DOM elements were never added. I don't personally know the reasons for the new behavior, but my guess would be that it's just an expansion of the language engine's capability. If you really want to know what the behavior is supposed to be, you could always read the standard: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Edit: Also, note that the method that is used to get the element is document.getElementById() which comes from the document object model. The method you're referring to is placing an id into the window object which can create conflicts by id. The standard defined method is to get the element from document and avoid putting things into the window. Using the window object in this manner would be similar to using a global variable (which is a bad practice re: http://www.javascripttoolbox.com/bestpractices/#namespace)
You can find your answer here: Can I Use an ID as a Variable Name?
In short, avoid it.
The reason it works is because the browser actually creates a variable window.document.myDiv
AVOID IT!
It seems like an amazing feature but I would recommend not using it because if you have divs with id same as that of some global JS variables, it would be conflicting and will also mess-up stuff in some other third party JS files that you include.
But You always have jQuery selectors always with you and not to forget the new querySelector feature in modern browsers :)

do I really need to call getElementById()? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
I just stumbled upon an unexpected but useful behavior in the browser: It creates a variable for every element that has an ID in my html code. So when I have:
<div id="ohlala"> ... </div>
the browser seem to run this code behind the scene:
var ohlala = document.getElementById("ohlala");
so I can easily change the text of that element by:
ohlala.innerHTML="test"
Try it online: http://jsfiddle.net/Facby/
The question is: why would I need to write the document.getElementById() bit myself? How portable is that code? I tried in Opera, FireFox and Chrome and it works! Can I rely on this functionality? Does the browser always create variables for every element with id? In that case I have to be more careful about the names that are used in my javascript code not to conflict with similar ids from the HTML, right?
When creating elements with IDs, the "window" object receives the specific attributes, that's why you can use variables directly, this behavior is deprecated and usually is wrote like this: window.ohlala.innerHTML = "...", this behavior is conserved by the browsers for compatibility with some older code on websites, but it is not recommended to use it in modern websites, always use .getElementById() method, this method is part of a W3C Standard, and you can use it in all modern browsers, in some very old browser versions and < IE7 it will not work. Learn more about DOM (Document Object Model) here: https://developer.mozilla.org/en-US/docs/DOM

need help replicating jQuery's addClass function

I would like to replicate jQuery's addClass function using plain javascript
So far, I have made this function:
function addClass(el,cl){
el.className+=(el.className?' ':'')+cl
}
It works well, but It uses this syntax:
addClass(element,class)
I want it to use this syntax:
element.addClass(class)
How can I do that?
thanks :)
There is no perfectly safe way to make element.addClass() work for all elements when element is a DOM element (not your own object like a jQuery object) in all browsers. Some frameworks have done this in the past and they have run into enough problems that some are moving away from doing that. I would not recommend doing it this way.
You are not in the business of browser compatibility or framework creation (not do you want to be) so even though it seems cleaner to extend the DOM objects, I would not recommend it. jQuery and YUI do not do it this way. They make a wrapper object that contains both the method and the DOM element reference.
If you want to read of some of the perils, here's a good reference on the subject: What's wrong with Extending the DOM?.
You can make it a prototype to extend the Element class.
Element.prototype.addClass = function(cl) {
this.className+=(this.className?' ':'')+cl;
}
example
As minitech pointed out though, this won't work reliably in all browsers (namely IE).

Is it a bad practice to reference Javascript objects from DOM elements?

As a "best practice" for front-end developers, is it bad to use the "control" property to reference back to the Javascript object?
Here's a link to the property in question:
https://developer.mozilla.org/en/XUL/Property/control
I've seen a lot of Javascript functions that reference DOM elements using selectors and then perform DOM manipulation that way. But what if we started by traversing through the DOM tree and we have the DOM element first?
EDIT 1
Okay, it seems like there are some interest here but no contributions for some reason. This started as a conversation between me and my co-worker. He was concerned about circular references and possible cases of losing references... does that apply here? I thought as long as we don't call delete <javascript object> then we're fine.
EDIT 2 I found this: JQuery methods and DOM properties
In my world right now, I'm using the Microsoft AJAX Library where we created multiple ScriptControls and put them on various pages; which in turn, (the ScriptControls) get "modified" by page's events and sometimes events of other ScriptControls. When pages need to do something with the DOM element, the Javascript would use the respective Javascript Object's methods.
However, it seems in JQuery (based on the other question), it's common to get the DOM element then use .get(0) to grab the JQuery object out of it (if it exists).
So I guess this is a witch hunt so far and there's still no right answer to my question :(
I know I'm still lacking an example but I'm not sure how to approach this.
I am not too sure what exactly you're referring to. Could you provide a simple code example? Otherwise, your question is a bit vague IMHO. I'll give it a shot anyways:
I do not understand why there would be any lost or circular references. The control attribute is just the id (string) of the "controlling" DOM Element, not a reference to the actual DOM Element. If you delete label.control it will no longer be associated with the other DOM Element.

Categories