Dear StackOverflow community,
I am new to jQuery and Javascript, and was wondering what the main differences between these two functions are:
document.getElementById('id').innerHTML =variable;
and
jQuery('#id').val(variable);
From my understanding, they are two different coding techniques, but when would I use one over the other? and why?
The two above examples are slightly different, but not in the way you're expecting.
innerHTML and .val() are not equivalent methods.
jQuery will try to use querySelector / querySelectorAll where appropriate when using the DOM selection jQuery("SELECTOR"). These are native methods, so look into them.
.val(variable) will set the value of the node found by jQuery("SELECTOR") to variable
innerHTML = variable will set the the HTML content of document.getElementById('id') to whatever variable is.
.val() - Set the value of each element in the set of matched elements.
innerHTML - innerHTML sets or gets the HTML syntax describing the element's descendants.
Related
So I encounter this situation often and I want to figure out a better way of going about it. I using the naming convention prefixing my jQuery elements with $ so that I can distinguish them from DOM elements. For example, the following:
$pointers = $('#pointer-box div.pointer');
The problem with that is, if I want to get the 3rd in the result as a jQuery, I have to do
$($pointers[2])
which looks awkward. Unless there's a better way of doing this?
You can use .eq() jQuery method
$pointers = $('#pointer-box div.pointer');
var element=$pointers.eq(2);
Given a jQuery object that represents a set of DOM elements, the .eq()
method constructs a new jQuery object from one element within that
set. The supplied index identifies the position of this element in the
set.
I've recently discovered a very fundamental difference between the 2 methods of setting custom DOM attributes in Javascript. The difference is in how the HTML5 Selectors API interacts with those attributes (ie, in document.querySelector() and friends).
<button id="b3">View</button>
<script>
document.getElementById('b3').shape = 'square';
console.log( document.querySelector('*[shape]') ); // FAIL: returns null
document.getElementById('b3').setAttribute('shape','square');
console.log( document.querySelector('*[shape]') ); // WORKS: returns element
</script>
So basically if you apply attributes to an element without using .setAttribute() then you cannot later select the element by the attribute name.
BTW. This behaviour is consistent across browsers which makes me think it might be addressed by the standard, however I can't see it:
http://www.w3.org/TR/css3-selectors/#attribute-selectors
http://www.w3.org/TR/selectors-api/
The selectors API standard doesn't appear to care:
Selectors allow the representation of an element's attributes. When a
selector is used as an expression to match against an element,
attribute selectors must be considered to match an element if that
element has an attribute that matches the attribute represented by the
attribute selector.
The entire attribute matching rule seems to boil down to "if the element has an attribute" and you would think that someElement.someAttribute = something would meet the criteria of "having an attribute" but for whatever reason it doesn't.
My question is basically why the difference? Is it actually part of a standard or just an identical implementation quirk in all the major browsers (IE11, FF38 and Chrome 43)?
The reason is very simple - getElementById and all of those kind return an Element Object (see specs: http://www.w3schools.com/jsref/met_document_getelementbyid.asp)
Which means you set property shape on an object. Then you try to do a query selector, but you haven't modified the html that's queried. They are different things.
I have:
<div id="myDiv1"></div>
<div id="myDiv2"></div>
In JavaScript, I can set div innerHTML by writing:
myDiv1.innerHTML = "myDiv1, Hi!"
or
document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!"
Why should I use document.getElementById when I can simply use element Id ? Is this working every time or only in some special scenarios (like simple sample)?
thanks,
Mike
Why should I use document.getElementById when I can simply use element Id ?
To avoid conflicts. The global namespace on browsers is incredibly crowded, all sorts of things are dumped in there, including (as you've found) globals referring to any element with an id (so-called "automatic globals").
In contrast, getElementById only does what it says, finds an element by its id; it's more constrained. (Other than bugs in old versions of IE, which also looked at elements with name attributes.)
when you write
myDiv1.innerHTML = "myDiv1, Hi!"
you are calling window object, so actual call is like this
window.myDiv1.innerHTML = "myDiv1, Hi!"
This behavior is deprecated now and to be avoided. Instead we should use
document.getElementById`
I recently found on this javascript tip :
element_number = Array.prototype.indexOf.call(element_1, element_2);
It allows developers to use the indexOf method on an object wich is not an Array.
I would like to know if it is possible to use a similar syntax to call the getElementById method but not on the whole document (document.getElementById), just on an element like this :
my_div_2 = document.prototype.getElementById.call(div_1, "id_of_my_div_2");
The idea is that my document contains tabs and elements having the same id can be present several times in the document.
If it is not possible, did somebody write a function doing that :
Search in an element another element by id.
No, but you can accomplish what you want using querySelector instead.
my_div_2 = div_1.querySelector("#id_of_my_div_2");
Not supported in IE6/7.
Docs: MDN element.querySelector()
That said, duplicate IDs are invalid.
This technique is useful if the same script is used on different pages where the ID may or may not be in a particular container.
No. The getElementById method must be applied on objects of type Document, otherwise it would throw a WRONG_THIS_VALUE exception. You could try it with
myDiv1 = document.getElementById("div1");
myDiv2 = document.getElementById.call(myDiv1, "div2"); // no ".prototype"!
This makes no sense as only one element with a given id is possible in a document.
So the only right syntax would be
my_div_2 = document.getElementById("id_of_my_div_2");
Don't reuse an id in a document. You probably can achieve the desired result using classes instead of id.
Before jQuery I would have used something like the following code to set a class on an element:
document.getElementById("MyElementID").className = 'MyClassName';
This has the intended behaviour of replacing anything that was there before my new class name MyClassName
In jQuery the equivalent seems to be:
$('#MyElementID').attr('class', 'MyClassName')
But, we also have the in-built class functions, addClass(), removeClass() and toggleClass(). So to achieve the same effect, I would say:
$('#MyElementID').removeClass().addClass('MyClassName');
Obviously, the first jQuery example is more concise and requires just one function call (to attr, instead of addClass() and removeClass())
Can we also work on the assumption that I can't use prop as its an earlier (and currently unchangeable) version that I'm working with.
So what would you say is the preferred approach? Does the second sample give me anything over and above the first?
Many thanks in advance.
The addClass(), removeClass() and has() methods of jQuery use the className property of the element. The big advantage they offer is that they allow you to add or remove a class without affecting the other class names set.
The attr() method uses something like this:
document.getElementById("MyElementID")[name] = value;
For cases that you only need one class name, the attribute method will be probably faster. I personally however find the addClass method more elegant and easier to adapt if you need to add more class names in the future.
I think you should check the performance of all these functions. personally i think prop method is fastest ( introduced in v1.6)
see here the performance jQuery().attr vs jQuery().data vs jQuery().prop
http://jsperf.com/jquery-data-vs-jqueryselection-data/8
The difference is in this guy:
<div class="a_class another_class a_third_class">
attr('class','no_other_classes_now') <-- will replace everything in the class attribute even if there are multiple space separated classes. It's probably the lightest-weight of JQ methods for doing this since it's just using DOM methods that already worked properly across browsers for over a decade now.
.removeClass('a_third_class') will remove a class, leaving other classes intact.
.addClass('a_fourth_class') will add a space-separated class without replacing other classes.
^^ These two would have to do more work for a simple class overwrite than attr since they need to do find/replace type operations.
Prop is for changing properties of DOM elements that don't have HTML representatives like the window object (not likely to be useful very often due to other convenience methods) or that would be confusing because different attribute strings can mean different things. Like simply having the attribute "checked" without an equal sign or value being equivalent to checked="checked" or checked="true" as far as the boolean (true/false only) JS property is concerned in certain flavors of HTML. With prop you'll get the javascript property and not necessarily whatever is considered to be between the quotes of the actual HTML element.
When you're not in that type of situation, I would stick with the attr method. The whole point of prop seems to be to take work from the old attr method so I'd be surprised if it was faster in most cases. More importantly it's common and easy to read.