I have the following code that I'm using to create a micro-library of sorts (similar to JQuery, but with only the stuff I need).
window.$ = function(selector, context, undefined)
{
var getSelectorTest = function(selector, context, undefined)
{
var el;
var selector_key = selector.slice(0, 1),
matches = {
'#': 'getElementById',
'.': 'getElementsByClassName',
'#': 'getElementsByName',
'=': 'getElementsByTagName',
'*': 'querySelectorAll'
}[selector_key],
selector_value = selector.slice(1);
//add fallback for getElementsByClassName is not supported e.g. IE8
if(matches === 'getElementsByClassName' && !document.getElementsByClassName)
{
matches = 'querySelectorAll';
selector_value = selector;
}
// now pass the selector without the key/first character
el = (((context === undefined) ? document: context)[matches](selector_value));
return el;
};
var elem = getSelectorTest(selector, context, undefined);
//Extend elem before returning it
elem.attr = function(name, value) {
if(value)
{
this.setAttribute(name, value);
return this;
}
else
{
return this.getAttribute(name);
}
return elem;
};
Then when I run the following code:
<script>
domReady(function(){ //https://github.com/cms/domready
var el_1 = $('#container-1');
el_1.attr("data-test", "random_value");
});
</script>
I get the following when using IE8:
<div id="container-1" attr="function(name, value) {
if(value)
{
this.setAttribute(name, value);
return this;
}
else
{
return this.getAttribute(name);
}
}" data-test="random_value">
Of course, this isn't the case when I use Chrome and Firefox (I get the output as expected i.e. <div id="container-1" data-test="random_value">). How can I fix this?
Note: I'm using 'HTML' tab of the IE8 Developer Tools (F12) to verify this.
Instead of attaching the attr() function to the selected element (which IE8 apparently interprets as setting an attribute on the element itself) you might have better luck attaching it to the prototype of the Element object.
Element.prototype.attr = function(name,value){ ...
Related
I am trying to go through an element and get all the attributes of that element to output them, for example an tag may have 3 or more attributes, unknown to me and I need to get the names and values of these attributes. I was thinking something along the lines of:
$(this).attr().each(function(index, element) {
var name = $(this).name;
var value = $(this).value;
//Do something with name and value...
});
Could anyone tell me if this is even possible, and if so what the correct syntax would be?
The attributes property contains them all:
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
What you can also do is extending .attr so that you can call it like .attr() to get a plain object of all attributes:
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
Usage:
var $div = $("<div data-a='1' id='b'>");
$div.attr(); // { "data-a": "1", "id": "b" }
Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.
Vanilla JS:
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
Vanilla JS with Array.reduce
Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
This function expects a jQuery object, not a DOM element.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Underscore
Also works for lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to #AlJey for that one.
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Test page
At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden) and enumerated attributes (contenteditable="").
A debugging script (jquery solution based on the answer above by hashchange)
function getAttributes ( $node ) {
$.each( $node[0].attributes, function ( index, attribute ) {
console.log(attribute.name+':'+attribute.value);
} );
}
getAttributes($(this)); // find out what attributes are available
with LoDash you could simply do this:
_.transform(this.attributes, function (result, item) {
item.specified && (result[item.name] = item.value);
}, {});
Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.
$("#myTestDiv").click(function(){
var attrs = document.getElementById("myTestDiv").attributes;
$.each(attrs,function(i,elem){
$("#attrs").html( $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myTestDiv" ekind="div" etype="text" name="stack">
click This
</div>
<div id="attrs">Attributes are <div>
Simple solution by Underscore.js
For example: Get all links text who's parents have class someClass
_.pluck($('.someClass').find('a'), 'text');
Working fiddle
My suggestion:
$.fn.attrs = function (fnc) {
var obj = {};
$.each(this[0].attributes, function() {
if(this.name == 'value') return; // Avoid someone (optional)
if(this.specified) obj[this.name] = this.value;
});
return obj;
}
var a = $(el).attrs();
Here is a one-liner for you.
JQuery Users:
Replace $jQueryObject with your jQuery object. i.e $('div').
Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Vanilla Javascript Users:
Replace $domElement with your HTML DOM selector. i.e document.getElementById('demo').
Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Cheers!!
The DOMTokenList and DOMSettableTokenList interfaces (MDN, WHATWG) provide methods for manipulating ordered sets of string tokens represented by space-delimited strings. They are most commonly used in the form of the Element.prototype.classList property, a DOMTokenList which reflects the class attribute of an associated element.
var div = document.createElement('div');
div.setAttribute('class', 'hello world goodnight moon');
var list = div.classList;
console.assert(list.length === 4);
console.assert(list[0] === 'hello');
console.assert(list.item(1) === 'world');
console.assert(list.contains('moon') === true);
console.assert(list.contains('mars') === false);
list.remove('world', 'earth', 'dirt', 'sand');
list.add('hello', 'mars');
list.toggle('goodnight');
console.assert(div.getAttribute('class') === 'hello moon mars');
I'm working on a custom element (HTML5Rocks, W3C Draft) which displays a real-time feed of the activity of specified Stack Overflow users. This list of users is specified in an ids attribute, and may be updated at any time.
<so-users ids="1114 22656 106224"></so-users>
document.querySelector('so-users').setAttribute('ids', '23354 115866');
Instead of requiring users to manipulate this attribute directly, I would like to have an .ids property providing a DOMTokenList that they can use instead. Ideally this would be directly associated with the attribute, but an unbound DOMSettableTokenList instance that I have to manually bind would also be fine.
document.querySelector('so-users').ids.add('17174');
Unfortunately, I have been unable to find any way to create a DOMTokenList instance. The definition is not a constructor, and directly creating an object using its prototype results in errors when I call any associated methods:
new DOMTokenList; // TypeError: Illegal constructor
new DOMSettableTokenList; // TypeError: Illegal constructor
var list = Object.create(DOMSettableTokenList.prototype, {
value: { value: 'hello world' }
});
console.assert(list instanceof DOMTokenList);
console.assert(list instanceof DOMSettableTokenList);
list.item(0); // TypeError: Illegal invocation
function TokenListConstructor() {
this.value = 'hello world';
}
TokenListConstructor.prototype = DOMSettableTokenList.prototype;
var list = new TokenListConstructor;
console.assert(list instanceof DOMTokenList);
console.assert(list instanceof DOMSettableTokenList);
list.add('moon'); // TypeError: Illegal invocation
How can I construct a new DOMTokenList or DOMSettableTokenList instance?
You cannot create an DOMTokenList or an DOMSettableTokenList directly. Instead you should use the class attribute to store and retrieve your data and perhaps map an ids attribute of your DOM element to the classList property.
var element = document.querySelector('so-users');
element.ids = element.classList;
You can use relList according to the documentation but classList is more supported, the only drawback is that you might run into issues if one of your ids matches a class name so set an inline style to hide the element just in case.
For a custom component compatibility should be a concern (classList is present in IE>=10, Firefox 3.6, Chrome 8, Opera 11.5 and Safari 5.1, see http://caniuse.com/#feat=classlist) so if compatibility is in your requirements use the another solution posted below.
If you cannot use clases or classList and/or must use the ids attribute you should implement a custom function according to the spec with the following properties as functions.
item()
contains()
add()
remove()
toggle()
This is an example implementation of such functionality.
var TokenList = function (ids) {
'use strict';
var idsArray = [],
self = this,
parse = function (id, functionName, cb) {
var search = id.toString();
if (search.split(' ').length > 1) {
throw new Error("Failed to execute '" + functionName + "' on 'TokenList': The token provided ('" + search + "') contains HTML space characters, which are not valid in tokens.');");
} else {
cb(search);
}
};
function triggerAttributeChange() {
if (self.tokenChanged && typeof self.tokenChanged === 'function') {
self.tokenChanged(idsArray.toString());
}
}
if (ids && typeof ids === 'string') {
idsArray = ids.split(' ');
}
self.item = function (index) {
return idsArray[index];
};
self.contains = function (id) {
parse(id, 'contains', function (search) {
return idsArray.indexOf(search) !== -1;
});
};
self.add = function (id) {
parse(id, 'add', function (search) {
if (idsArray.indexOf(search) === -1) {
idsArray.push(search);
}
triggerAttributeChange();
});
};
self.remove = function (id) {
parse(id, 'remove', function (search) {
idsArray = idsArray.filter(function (item) {
return item !== id;
});
triggerAttributeChange();
});
};
self.toggle = function (id) {
parse(id, 'toggle', function (search) {
if (!self.contains(search)) {
self.add(search);
} else {
self.remove(search);
}
});
};
self.tokenChanged = null;
self.toString = function () {
var tokens = '',
i;
if (idsArray.length > 0) {
for (i = 0; i < idsArray.length; i = i + 1) {
tokens = tokens + idsArray[i] + ' ';
}
tokens = tokens.slice(0, tokens.length - 1);
}
return tokens;
};
};
Set an 'ids' property in your element with a new instance of this function and finally you must bound the targeted attribute to the property listening to changes to the element and updating the property o viceversa. You can do that with a mutation observer.
See firing event on DOM attribute change and https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
var attachTokenList = function (element, prop, initialValues) {
'use strict';
var initValues = initialValues || element.getAttribute(prop),
MutationObserver = window.MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
observer,
config,
cancelMutation = false;
function createTokenList(values) {
var tList = new TokenList(values);
tList.tokenChanged = function () {
element.setAttribute(prop, element[prop].toString());
cancelMutation = true;
};
element[prop] = tList;
}
createTokenList(initValues);
observer = new MutationObserver(function (mutation) {
var i,
mutationrec,
newAttr;
if (mutation.length > 0 && !cancelMutation) {
for (i = 0; i < mutation.length; i = i + 1) {
mutationrec = mutation[i];
if (mutationrec.attributeName === prop && element[prop]) {
newAttr = element.getAttribute(prop);
createTokenList(newAttr);
}
}
}
cancelMutation = false;
});
config = {
attributes: true
};
observer.observe(element, config);
};
Testing to see if it works
<so-users ids="1234 5678"></so-users>
<button onclick="clickButton1()">Add 7890</button>
<button onclick="clickButton2()">Set to 3456</button>
<button onclick="clickButton3()">Add 9876</button>
Inside a script tag
var elem = document.querySelector('so-users');
attachTokenList(elem, 'ids')
function clickButton1 () {
elem.ids.add('7890');
}
function clickButton2 () {
elem.setAttribute('ids', '3456');
}
function clickButton3 () {
elem.ids.add('9876');
}
Clicking the buttons in sequence set the ids attribute to '3456 9876'
You can get an instance of DOMTokenList with this function:
function newDOMTokenList(initialTokens) {
const tmp = document.createElement(`div`);
const classList = tmp.classList;
if (initialTokens) {
initialTokens.forEach(token => {
classList.add(token);
});
}
return classList;
}
We can 'steal' the DOMTokenList from a div, since it does not affect the current document until you choose to insert the element (for example by using insertAdjacentElement) and it will be garbage collected since we do not keep any references to the variable tmp.
Then you can use your list:
var list = newDOMTokenList(['a', 'b']);
list.add('c');
list.contains('d'); // false
list.contains('b'); // true
list.item(1) // 'b'
list instanceof DOMTokenList // true
// etc...
// render it to a string
var soUsers = document.querySelector('so-users');
soUsers.setAttribute('ids', list.toString());
You can even add a MutationObserver to the tmp element and get callbacks whenever the classList changes:
function newDOMTokenList(initialTokens, changed) {
const tmp = document.createElement('div');
const classList = tmp.classList;
if (initialTokens) {
initialTokens.forEach(token => {
classList.add(token);
});
}
if (changed) {
const observer = new MutationObserver((mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.attributeName === 'class') {
changed();
}
}
});
observer.observe(tmp, {attributes: true});
}
return classList;
}
This, however, will cause the tmp div to never be garbage collected, since the MutationObserver needs to keep a reference to it.
Utilizing Custom Elements - Adding JS properties and methods initialization approach , HTMLElement.dataset
, try
var XFooProto = Object.create(HTMLElement.prototype);
// 1. Give x-foo a foo() method.
XFooProto.contains = function(id) {
var data = JSON.parse(this.dataset.ids);
return data.some(function(_id) {
return id == _id
})
};
XFooProto.add = function(id) {
var data = JSON.parse(this.dataset.ids);
if (!this.contains(id)) {
data.push(id);
};
return data
};
XFooProto.remove = function(id) {
var data = JSON.parse(this.dataset.ids);
if (this.contains(id)) {
for (var _id in data) {
if (data[_id] === id) {
data.splice(_id, 1)
}
};
};
return data
};
XFooProto.ids = function() {
return this.dataset.ids
};
// 2. Define a property read-only "bar".
// Object.defineProperty(XFooProto, "ids", {value: this});
// 3. Register x-foo's definition.
var XFoo = document.registerElement('x-foo', {prototype: XFooProto});
// 4. Instantiate an x-foo.
var xfoo = document.createElement('x-foo');
xfoo.dataset.ids = '["23354", "115866"]';
// 5. Add it to the page.
document.body.appendChild(xfoo);
console.log(xfoo.add("123")); // `["23354", "115866", "123"]`
console.log(xfoo.remove("123")); // `["23354", "115866"]`
console.log(xfoo.contains("123")); // `false`
console.log(xfoo.contains("23354")); // `true`
console.log(xfoo.ids()); // `["23354", "115866"]` , type : `String`
var pre = document.getElementsByTagName("pre")[0]
pre.innerText = JSON.stringify(JSON.parse(xfoo.dataset.ids), null, 4);
<pre></pre>
I am trying to go through an element and get all the attributes of that element to output them, for example an tag may have 3 or more attributes, unknown to me and I need to get the names and values of these attributes. I was thinking something along the lines of:
$(this).attr().each(function(index, element) {
var name = $(this).name;
var value = $(this).value;
//Do something with name and value...
});
Could anyone tell me if this is even possible, and if so what the correct syntax would be?
The attributes property contains them all:
$(this).each(function() {
$.each(this.attributes, function() {
// this.attributes is not a plain object, but an array
// of attribute nodes, which contain both the name and value
if(this.specified) {
console.log(this.name, this.value);
}
});
});
What you can also do is extending .attr so that you can call it like .attr() to get a plain object of all attributes:
(function(old) {
$.fn.attr = function() {
if(arguments.length === 0) {
if(this.length === 0) {
return null;
}
var obj = {};
$.each(this[0].attributes, function() {
if(this.specified) {
obj[this.name] = this.value;
}
});
return obj;
}
return old.apply(this, arguments);
};
})($.fn.attr);
Usage:
var $div = $("<div data-a='1' id='b'>");
$div.attr(); // { "data-a": "1", "id": "b" }
Here is an overview of the many ways that can be done, for my own reference as well as yours :) The functions return a hash of attribute names and their values.
Vanilla JS:
function getAttributes ( node ) {
var i,
attributeNodes = node.attributes,
length = attributeNodes.length,
attrs = {};
for ( i = 0; i < length; i++ ) attrs[attributeNodes[i].name] = attributeNodes[i].value;
return attrs;
}
Vanilla JS with Array.reduce
Works for browsers supporting ES 5.1 (2011). Requires IE9+, does not work in IE8.
function getAttributes ( node ) {
var attributeNodeArray = Array.prototype.slice.call( node.attributes );
return attributeNodeArray.reduce( function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
jQuery
This function expects a jQuery object, not a DOM element.
function getAttributes ( $node ) {
var attrs = {};
$.each( $node[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
} );
return attrs;
}
Underscore
Also works for lodash.
function getAttributes ( node ) {
return _.reduce( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
return attrs;
}, {} );
}
lodash
Is even more concise than the Underscore version, but only works for lodash, not for Underscore. Requires IE9+, is buggy in IE8. Kudos to #AlJey for that one.
function getAttributes ( node ) {
return _.transform( node.attributes, function ( attrs, attribute ) {
attrs[attribute.name] = attribute.value;
}, {} );
}
Test page
At JS Bin, there is a live test page covering all these functions. The test includes boolean attributes (hidden) and enumerated attributes (contenteditable="").
A debugging script (jquery solution based on the answer above by hashchange)
function getAttributes ( $node ) {
$.each( $node[0].attributes, function ( index, attribute ) {
console.log(attribute.name+':'+attribute.value);
} );
}
getAttributes($(this)); // find out what attributes are available
with LoDash you could simply do this:
_.transform(this.attributes, function (result, item) {
item.specified && (result[item.name] = item.value);
}, {});
Using javascript function it is easier to get all the attributes of an element in NamedArrayFormat.
$("#myTestDiv").click(function(){
var attrs = document.getElementById("myTestDiv").attributes;
$.each(attrs,function(i,elem){
$("#attrs").html( $("#attrs").html()+"<br><b>"+elem.name+"</b>:<i>"+elem.value+"</i>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="myTestDiv" ekind="div" etype="text" name="stack">
click This
</div>
<div id="attrs">Attributes are <div>
Simple solution by Underscore.js
For example: Get all links text who's parents have class someClass
_.pluck($('.someClass').find('a'), 'text');
Working fiddle
My suggestion:
$.fn.attrs = function (fnc) {
var obj = {};
$.each(this[0].attributes, function() {
if(this.name == 'value') return; // Avoid someone (optional)
if(this.specified) obj[this.name] = this.value;
});
return obj;
}
var a = $(el).attrs();
Here is a one-liner for you.
JQuery Users:
Replace $jQueryObject with your jQuery object. i.e $('div').
Object.values($jQueryObject.get(0).attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Vanilla Javascript Users:
Replace $domElement with your HTML DOM selector. i.e document.getElementById('demo').
Object.values($domElement.attributes).map(attr => console.log(`${attr.name + ' : ' + attr.value}`));
Cheers!!
Ok, so I have this function designed to return a desired computed style from a specified element. It works in all desktop browsers that I have tested, however, it does not work in mobile safari. If I log the getComputedStyle call back to the console it is a [object CCStyleDeclaration] which is great, but when I log the getPropertyValue call it simply returns "null" instead of the correct style. Any help would be fantastic. Thanks!
Utils.getStyle = function(element, style){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(element, "").getPropertyValue(style);
}else if(element.currentStyle){
style = style.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = element.currentStyle[style];
};
return strValue;
};
In the case my comment about window.getComputedStyle vs document.defaultView.getComputedStyle has any substance, I use this function in my own library:
getComputedStyle : function(element){
var styles = element.currentStyle || getComputedStyle(element, null);
return styles;
}
Adapted to your function signature:
Utils.getStyle = function(element, style){
var styles = element.currentStyle || getComputedStyle(element, null);
// Prevent a 'Cannot read property X of null' error
if(styles != null){
return styles[style];
} else {
return null;
}
}
I can't test this in iOS unfortunately, but I'm interested to know if it works.
i have been using jquery for a while now but only thing i know about jquery is probably a dozen of functions that get my job done. but i want to understand how jquery evolved from simpl plain javascript i.e how
$("#xyz").val();
is converted to
document.getElementById('xyz').value;
i have searched for my answer on the web but most of the writers are happy to show how you can hook on to different DOM elements with jquery, selector details etc. but nothing can be found about how actually the transition was made. can anyone refer me to some tutorial where i can get my required material?
thanks
jQuery is not a compiler. jQuery does not get compiled into javascript.
.val is a method of an object. The jQuery object.
Specifically it is
function (value) {
if (!arguments.length) {
var elem = this[0];
if (elem) {
if (jQuery.nodeName(elem, "option")) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
// We need to handle select boxes special
if (jQuery.nodeName(elem, "select")) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if (index < 0) {
return null;
}
// Loop through all the selected options
for (var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++) {
var option = options[i];
// Don't return options that are disabled or in a disabled optgroup
if (option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if (one) {
return value;
}
// Multi-Selects return an array
values.push(value);
}
}
return values;
}
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
if (rradiocheck.test(elem.type) && !jQuery.support.checkOn) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction(value);
return this.each(function (i) {
var self = jQuery(this),
val = value;
if (this.nodeType !== 1) {
return;
}
if (isFunction) {
val = value.call(this, i, self.val());
}
// Treat null/undefined as ""; convert numbers to string
if (val == null) {
val = "";
} else if (typeof val === "number") {
val += "";
} else if (jQuery.isArray(val)) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
if (jQuery.isArray(val) && rradiocheck.test(this.type)) {
this.checked = jQuery.inArray(self.val(), val) >= 0;
} else if (jQuery.nodeName(this, "select")) {
var values = jQuery.makeArray(val);
jQuery("option", this).each(function () {
this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0;
});
if (!values.length) {
this.selectedIndex = -1;
}
} else {
this.value = val;
}
});
}
If we break the above wall down we can get
function (value) {
if (arguments.length === 0) {
return (this[0].value || "")
}
this.value = val;
return this;
}
Of course jQuery has a lot more code to deal with various edge cases and special things.
In essence jQuery takes a selector. finds the elements. Stores them internally then returns you an object.
This object has all kinds of methods that allow you to mutate the underlying dom objects stored internally. .val is one of them.
There are plenty of articles on how jQuery works (there are screencasts too).
jQuery, as you've noticed, is basically a bunch of methods operating on an array of elements. It is also intended to normalize browser differences under the hood.
Take the basic usage $("#xyz").val();
I can even tell you what jQuery is doing behind the scenes, but I don't think you really want to know. :)
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// ...
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// ...
},
// ...
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
So basically $(selector) means newjQuery.fn.init(selector), it's just a shortcut for easier typing (and also to prevent the "bug" where fogetting new binds this to the global object, instead of the current instance).
Also, the so-called plug-ins added as jQuery.fn.ext are mapped to jQuery.fn.init.prototype as you can see in the last line, it's another shortcut. So when you call $(selector) everything that is added to jQuery.fn will also be on jQuery.fn.init.prototype and so the new instance will have those methods as $(selector).ext(...).
// as you use it today
jQuery.fn.plugin = function ( ... ) { ... }
$(selector).plugin( ... )
// as it would be without shortcuts
jQuery.fn.init.prototype.plugin = function ( ... ) { ... }
(new jQuery.fn.init(selector)).plugin( ... )