Find nodes from the HTML with a CSS selector:
u('ul#demo li')
u(document.getElementById('demo'))
u(document.getElementsByClassName('demo'))
u([ document.getElementById('demo') ])
u( u('ul li') )
u('<a>')
u('li', context)
The first parameter can be:
- A text CSS selector
- A single HTML Node. This is specially useful in events where you can just pass
this
- A NodeList or other similar objects that can be converted to an array
- An array of nodes*
- Another Umbrella instance
- An HTML fragment as a string
- Nothing
The second parameter is only for the CSS selector, which indicates a portion of the DOM where the selector is applied. For example, with u('li', u('ul').first())
it will find all of the li
from the first ul
.
* actually it can be an array of anything you want as in ["a", "b"]
, however this is not officially supported and might change at any moment
You should use
u('#demo')
instead ofu(document.getElementById('demo'))
, internally it's optimized to do this in a fast way. That was only an example of what's possible.
An instance of Umbrella JS so you can chain it to any of the other methods.
Select all of the list elements that are children of ul
var lis = u('ul > li'); // Same as u('ul').children('li');
Find all of the headers from the page to create a Table of Contents:
var headers = u('h1, h2, h3, h4, h5, h6');
Generate a link on the fly:
var link = u('<a>').addClass('main').attr({ href: '/hello' });
You can use this to generate many kind of elements on the fly. For example, for a simple grocery list (using ES6 for simplicity):
var fruits = ['apple', 'strawberry', 'pear', 'banana'];
var list = u('<ul>').append(fruit => `<li>${ fruit }</li>`, fruits);
u('body').append(list);
This section is inspired by Bliss.js' vanilla methods
There are many native methods and properties that you can use. These can be called straight in the .first()
or .last()
elements, a .nodes
element or you can loop every element to call them. For example:
// Single element from .nodes
u('h1').nodes[0].classList.add('vanilla');
// Single element
u('h1').first().classList.add('vanilla', 'test');
// Multiple elements. Note that the order is different from jQuery
u('h2').each(function(el){
el.classList.add('vanilla', 'test');
});
And for the arrays it's similar, you can call any array method on u().nodes
since this is literally an array:
u('h2').nodes.forEach();
var mapped = u('h2').nodes.map();
var filtered = u('h2').nodes.filter();
var good = u('h2').nodes.some();
However, there are also some advantages of using Umbrella's methods instead of native methods. For example, with .addClass()
vs native classList.add()
:
- error prevention: if nodes.length = 0, the single-element way will fail in the above implementation (since first() and nodes[0] are null)
- cross-browser: the classList.add() with multiple elements is not compatible with IE10-11 & Android 4.3-
- chainable:
u('<div>').each(...).addClass(...);
- more flexibility: there are many ways to specify multiple classes with addClass, and only one way to specify them on the native way. Imagine that you have an array of classes, with the native method this becomes a nightmare. This is what it means to be flexible:
u('h2').addClass('vanilla', 'test'); // It accepts multiple parameters
u('h2').addClass(['vanilla', 'test']); // Also accept an array
u('h2').addClass(['vanilla'], ['test']); // Or multiple arrays
u('h2').addClass('vanilla, test'); // Strings with space and/or comma
u('h2').addClass('vanilla', ['test'], 'one, more' ); // Or just whatever
So it's convenient that you know these limitations and act accordingly. Try to use native methods where it makes sense, then Umbrella's methods where it's better suited or then create your own methods when you need it.
You can check how many elements are matched with .length
:
// Check how many <a> are in the page
alert(u('a').length);
Add html class(es) to all of the matched elements.
.addClass('name1')
.addClass('name1 name2 nameN')
.addClass('name1,name2,nameN')
.addClass('name1', 'name2', 'nameN')
.addClass(['name1', 'name2', 'nameN'])
.addClass(['name1', 'name2'], ['name3'], ['nameN'])
.addClass(function(node, i){ return 'name1'; })
.addClass(function(){ return 'name1'; }, function(){ return 'name2'; })
name1
, name2
, nameN
: the class name (or variable containing it) to be added to all of the matched elements. It accepts many different types of parameters (see above).
u
: returns the same instance of Umbrella JS
Add the class main
to all the <h2>
from the page:
u("h2").addClass("main");
Add the class toValidate
and ajaxify
to all the <form>
present in the page:
u("form").addClass("toValidate", "ajaxify");
Add a class to indicate order:
u("ul li").addClass(function(node, i){ return `el-${i + 1}`; });
<ul>
<li class="el-1">...</li>
<li class="el-2">...</li>
<li class="el-3">...</li>
</ul>
.hasClass() finds if the matched elements contain the class(es).
.removeClass() deletes class(es) from the matched elements.
.toggleClass() adds or removes the class
Add some html as a sibling after each of the matched elements.
.after(html)
.after('<div>')
.after(u('<div>'))
.after(u('<div>').first()) // Same as document.createElement('div')
.after(u('<div></div><div></div>'))
.after(function(){})
.after(function(el){}, elements)
.after(function(el){}, 10)
html = ""
:
- Any of these elements:
- string containing the html that is going to be inserted
- instance of Umbrella
- HTML node
- array containing HTML nodes
- A callback that returns any of the previous. It gets passed these parameters:
- el: the current element from the elements parameter, {} if none is specified and i if elements is number
- i: the index of the current element
elements = [{}]
(optional): It can be any of the following:
- An array of elements that will be passed to the callback. The callback is executed once per element, and all of them are added consecutively.
- A CSS selector, so the function will be executed once per matched element.
- A number, in which case the function will be executed that number of times
u
: returns the same instance of Umbrella JS
Add a separator <hr>
after each of the main titles h1:
u("h1").after("<hr>");
Add three elements after the link. All of these methods are equivalent:
// Add them all like a single string
u("a.main").after("<a>One</a><a>Two</a><a>Three</a>");
// Add them in a chain
u("a.main").after("<a>Three</a>").after("<a>Two</a>").after("<a>One</a>");
// Add them with a function parameter
var cb = function(txt){ return "<a>" + txt + "</a>" };
u("a.main").after(cb, ["One", "Two", "Three"]);
// Same as the previous one but with ES6
u("a.main").after(txt => `<a>${ txt }</a>`, ["One", "Two", "Three"]);
They all result in:
<!-- previous data -->
<a class="main"></a>
<a>One</a>
<a>Two</a>
<a>Three</a>
You can also add some events to them by creating an html node:
function greeting(){ alert("Hello world"); }
u("a.main").after(function(){
return u('<a>').addClass('hi').on('click', greeting).html("Greetings!");
});
.before() Add some html before each of the matched elements.
.append() Add some html as a child at the end of each of the matched elements
.prepend() Add some html as a child at the beginning of each of the matched elements.
Add some html as a child at the end of each of the matched elements
.append(html)
.append('<div>')
.append(u('<div>'))
.append(u('<div>').first()) // Same as document.createElement('div')
.append(u('<div></div><div></div>'))
.append(function(){})
.append(function(el){}, elements)
.append(function(el){}, 10)
html = ""
:
- Any of these elements:
- string containing the html that is going to be inserted
- instance of Umbrella
- HTML node
- array containing HTML nodes
- A callback that returns any of the previous. It gets passed these parameters:
- el: the current element from the elements parameter, {} if none is specified and i if elements is number
- i: the index of the current element
elements = [{}]
(optional): It can be any of the following:
- An array of elements that will be passed to the callback. The callback is executed once per element, and all of them are added consecutively.
- A CSS selector, so the function will be executed once per matched element.
- A number, in which case the function will be executed that number of times
u
: returns the same instance of Umbrella JS
Add a footer to each of the articles
u("article").append("<footer>Hello world</footer>");
Add three elements to the list. All of these methods are equivalent:
// Add them all like a single string
u("ul").append("<li>One</li><li>Two</li><li>Three</li>");
// Add them in a chain
u("ul").append("<li>One</li>").append("<li>Two</li>").append("<li>Three</li>");
// Add them with a function parameter
var cb = function(txt){ return "<li>" + txt + "</li>" };
u("ul").append(cb, ["One", "Two", "Three"]);
// Same as the previous one but with ES6
u("ul").append(txt => `<li>${ txt }</li>`, ["One", "Two", "Three"]);
They all result in:
<ul>
<!-- previous data -->
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
You can also add some events to them by creating an html node:
function greet(){ alert("Hello world"); }
u("a.main").append(function(){
return u('<a>').addClass('hi').on('click', greet).html("Hey!");
});
.prepend() Add some html as a child at the beginning of each of the matched elements.
.before() Add some html before each of the matched elements.
.after() Add some html as a sibling after each of the matched elements.
Extract structured data from the DOM.
.array()
.array(callback)
callback = function(node, i){ return node.innerHTML }
: a callback to be called on each node. The returned value is the one set on the final version. If an array is returned then these elements are added to the set. However, if nothing or null is returned it removes them.
A simple javascript array consisting on the elements returned by the callback
<ul>
<li>Peter</li>
<li>Mery</li>
<li>John</li>
</ul>
Javascript (by default):
u('ul li').array();
// ['Peter', 'Mery', 'John']
Javascript (with custom callback):
u('ul li').array(function(node){
return { name: u(node).text() };
});
// [{ name: 'Peter' }, { name: 'Mery' }, { name: 'John' }]
Handle attributes for the matched elements
// GET
.attr('name');
// SET
.attr('name', 'value');
.attr('name', function(node, i){ return 'value'; });
.attr({ name1: 'value', name2: 'value2' });
GET
name
: the attribute that we want to get from the first matched element
SET
name
: the attribute that we want to set for all of the matched elements
value
: what we want to set the attribute to. If it's not defined, then we get the name
GET
string
: the value of the attribute
SET
u
: returns the same instance of Umbrella JS
You must understand that .attr()
will only retrieve the attributes, not the properties like checked
. To understand it better, check jQuery's attr() vs prop().
Each property is different so you should consult each case. For example, if you wanted to get the property checked
you could do:
u('.terms-os-service').is(':checked');
Get the alt of an image:
u('img.hero').attr('alt');
Set the src of all of the images:
u('img').attr({ src: 'demo.jpg' });
Add some kind of lazy-load with data-src
:
// Copy any "data-src" value, or just "src" to the "src" of the image:
u('img').attr('src', node => u(node).data('src') || u(node).attr('src'));
.data() handle data-* attributes for the matched elements
Add some html before each of the matched elements.
.before(html)
.before('<div>')
.before(u('<div>'))
.before(u('<div>').first()) // Same as document.createElement('div')
.before(u('<div></div><div></div>'))
.before(function(){})
.before(function(el){}, elements)
.append(function(el){}, 10)
html = ""
:
- Any of these elements:
- string containing the html that is going to be inserted
- instance of Umbrella
- HTML node
- array containing HTML nodes
- A callback that returns any of the previous. It gets passed these parameters:
- el: the current element from the elements parameter, {} if none is specified and i if elements is number
- i: the index of the current element
elements = [{}]
(optional): It can be any of the following:
- An array of elements that will be passed to the callback. The callback is executed once per element, and all of them are added consecutively.
- A CSS selector, so the function will be executed once per matched element.
- A number, in which case the function will be executed that number of times
u
: returns the same instance of Umbrella JS
Add a header to each of the articles
u("article").after("<header>Hello world</header>");
Add three elements before the link. All of these methods are equivalent:
// Add them all like a single string
u("a.main").before("<a>One</a><a>Two</a><a>Three</a>");
// Add them in a chain
u("a.main").before("<a>One</a>").before("<a>Two</a>").before("<a>Three</a>");
// Add them with a function parameter
var cb = function(txt){ return "<a>" + txt + "</a>" };
u("a.main").before(cb, ["One", "Two", "Three"]);
// Same as the previous one but with ES6
u("a.main").before(txt => `<a>${ txt }</a>`, ["One", "Two", "Three"]);
They all result in:
<a>One</a>
<a>Two</a>
<a>Three</a>
<a class="main"></a>
<!-- previous data -->
You can also add some events to them by creating an html node:
function greeting(){ alert("Hello world"); }
u("a.main").before(function(){
return u('<a>').addClass('hi').on('click', greeting).html("Greetings!");
});
.after() Add some html as a sibling after each of the matched elements.
.append() Add some html as a child at the end of each of the matched elements
.prepend() Add some html as a child at the beginning of each of the matched elements.
Get the direct children of all of the nodes with an optional filter
.children(filter);
filter
: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation
u
: returns an instance of Umbrella JS with the new children as nodes
Get the first <li>
of every <ul>
u("ul").children('li:first-child');
.parent() get all of the direct parents
.find() get all of the descendants of the matched nodes
.closest() get the first ascendant that matches the selector
Create a deep copy of the set of matched elements. Includes matched element node and all of its events as well as its children and all of their events by default.
u('.elementToClone').clone()
- The following extensions are enabled by default:
- events clone the events of all of the nodes. To disable it globally, add
u.prototype.mirror.events = false;
to your code. - select select input node values are copied to all cloned nodes. To disable globally, add
u.prototype.mirror.select = false;
to your code. - textarea textarea input node values are copied to all cloned nodes. To disable globally, add
u.prototype.mirror.textarea = false;
to your code.
- events clone the events of all of the nodes. To disable it globally, add
u
: returns the same instance of Umbrella JS
Clone a node and append to another.
<div class="container">
<div class="testClone1">Hello</div>
<div class="cloneDestination"></div>
</div>
var clone = u(".testClone1").clone();
u(".cloneDestination").append(clone);
Result:
<div class="container">
<div class="testClone1">Hello</div>
<div class="cloneDestination">
<div class="testClone1">Hello</div>
</div>
</div>
.append() add some html as a child at the end of each of the matched elements.
Find the first ancestor that matches the selector for each node
.closest(filter);
filter
: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation
u
: returns an instance of Umbrella JS with the new ancestors as nodes
Get the ul of every li
u("li").closest('ul');
.find() get all of the descendants of the matched nodes
.parent() get all of the direct parents
.children() get the direct children of all of the nodes with an optional filter
Handle data-* attributes for the matched elements
// GET
.data('name');
// SET
.data('name', 'value');
.data({ name1: 'value', name2: 'value2' });
GET
name
: the data-* attribute that we want to get from the first matched element
SET
name
: the data-* attribute that we want to set for all of the matched elements
value
: what we want to set the attribute to. If it's not defined, then we get the name
GET
string
: the value of the data-* attribute
SET
u
: data-* returns the same instance of Umbrella JS
Get the value for data-id:
<ul>
<li data-id='0'>First</li>
<li data-id='1'>Second</li>
<li data-id='2'>Third</li>
</ul>
u('ul li').first().data('id'); // 0
Set the data-id of an element:
u('ul li').first().data({ id: '1' }); // <li data-id='1'>First</li>
u('ul li').first().data('id', '2'); // <li data-id='2'>First</li>
.attr() handle attributes for the matched elements
Loop through all of the nodes and execute a callback for each
.each(function(node, i){});
callback
: the function that will be called. It accepts two parameters, the node and the index. this
is Umbrella's instance so other methods like this.args()
and this.slice()
are available.
u
: returns an instance of Umbrella JS with the same nodes
Loop through all of the links and add them a target="_blank"
:
u('a').each(function(node, i){
u(node).attr({ target: '_blank' });
});
Remove all child nodes of the matched elements.
.empty();
This method doesn't accept any parameters
u
: Returns an instance of Umbrella JS with the empty nodes.
Removes all child nodes from all containers:
u("div.container").empty();
.remove() Removes the matched elements.
Remove all the nodes that doesn't match the criteria
.filter('a')
.filter(u('a'))
.filter(function(node, i){ return u(node).is('a'); })
filter
: it can be:
- CSS selector that each of the nodes must match to stay
- Instance of Umbrella with the elements to keep (the intersection will be kept)
- Function that returns a boolean with true to keep the element. It accepts two parameters,
node
andindex
, and the context ofthis
is the instance of Umbrella so methods likethis.slice()
are available
An instance of Umbrella with the nodes that passed the filter.
Get only the active links
var links = u('a').filter('.active');
Get all of the paragraphs with a link:
var paragraphs = u('p').filter(function(node){
return u(node).find('a').length > 0;
});
Get only the inputs with an answer above 5 and show an error:
u('input').filter(function(node, i){
if (parseInt(u(node).first().value) > 5) {
return true;
}
}).addClass('error');
.is() check whether one or more of the nodes is of one type
.not() remove all the nodes that match the criteria
Get all of the descendants of the nodes with an optional filter
.find(filter);
filter
: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation
An instance of Umbrella with the new children as nodes
Get all of the links within all the paragraphs
u("p").find('a');
Get the required fields within a submitting form:
u('form').on('submit', function(e){
var required = u(this).find('[required]');
});
.closest() get the first ascendant that matches the selector
.parent() get all of the direct parents
.children() get the direct child of the matched nodes
Retrieve the first of the matched nodes
.first();
This method doesn't accept any parameters
The first html node or false if there is none.
Retrieve the first element of a list:
var next = u("ul.demo li").first();
.last() retrieve the last matched element
This function is the same as on()
, but it executes the e.preventDefault()
so you don't need to do it. So these two are exactly the same:
u('form.login').on('submit', function(e){
e.preventDefault();
// logic
});
u('form.login').handle('submit', function(e){
// logic
});
.on() Calls a function when an event is triggered
.trigger() calls an event on all of the matched nodes
.off() Removes an event from matched nodes
Find if any of the matched elements contains the class passed:
.hasClass('name1');
.hasClass('name1 name2 nameN');
.hasClass('name1,name2,nameN');
.hasClass('name1', 'name2', 'nameN');
.hasClass(['name1', 'name2', 'nameN']);
.hasClass(['name1', 'name2'], ['name3'], ['nameN']);
.hasClass(function(){ return 'name1'; });
.hasClass(function(){ return 'name1'; }, function(){ return 'name2'; });
If more than one class is passed, they are checked with the AND condition similar to:
u("a").hasClass("button") && u("a").hasClass("primary");
name1
, name2
, nameN
: the class name (or variable containing it) to be matched to any of the matched elements. It accepts many different types of parameters (see above).
boolean
: returns true if all of the passed classes are found in any of the matched elements and false if they couldn't be found.
You can also check manually if it has several classes with the OR parameter with:
u('a').is('.button, .primary');
And with the AND parameter:
u('a').is('.button.primary');
Toggle the color of a button depending on the status
<a class="example button">Click me</a>
<script src="//umbrellajs.com/umbrella.min.js"></script>
<script>
u(".example").on('click', function() {
if(u(this).hasClass("error")) {
u(this).removeClass("error").html("Click me");
} else {
u(this).addClass("error").html("Confirm");
}
});
</script>
.addClass() adds html class(es) to each of the matched elements.
.removeClass() deletes class(es) from the matched elements.
Retrieve or set the html of the elements:
// GET
.html();
// SET
.html(html);
GET should pass no parameter so it retrieves the html.
SET
html
: the new value that you want to set. To remove it, pass an empty string: ""
GET
string
: the html of the first node
SET
u
: returns the same instance of Umbrella JS
Get the main title:
var title = u('h1').html();
Set the main title:
u('h1').html('Hello world');
.text() Retrieve or set the textContent of the elements
.attr() Handle attributes for the matched elements
Check whether any of the nodes matches the selector
.is('a')
.is(u('a'))
.is(function(){ return Math.random() > 0.5 })
filter
: it can be two things:
- CSS selector to check
- Instance of Umbrella with the elements to check
- Function that returns a boolean to check for each of the nodes. If one of them returns true, then the method
is()
returns true. It accepts two parameters,node
andindex
, and the context ofthis
is the instance of Umbrella so methods likethis.slice()
are available.
boolean: true if any of the nodes matches the selector or the function returns true, false otherwise.
Check if the current form needs to be validated
u('form.subscribe').on('submit', function(e) {
// Same as u('form.subscribe').hasClass('validate')
if (u(e.target).is('.validate')) {
validate();
}
// ...
});
.filter() remove unwanted nodes
.not() remove all the nodes that match the criteria
Get the last element from a list of elements.
.last();
This method doesn't accept any parameters
The last html node or false if there is none.
Retrieve the last element of a list:
var next = u("ul.demo li").last();
.first() retrieve the first matched element
Change the content of the current instance by looping each element
.map(function(){});
A single callback that returns the element(s) that are going to be kept:
var links = u('.special li').map(function(node, i){
if (parseInt(node.innerHTML) > 10) {
return '<a>' + u(node).data('id') + '</a>';
}
}).addClass('expensive');
It can return a value that evaluates to false, a single element, an string, an array or an Umbrella instance. It will remove duplicated nodes from the result.
Note: Umbrella JS is made to manipulate HTML nodes so it will consider the string "" and 0 as false and remove them. Return an HTML node or an HTML string to keep the elements.
An instance of Umbrella with the nodes passed
Get the parent elements (see .parent()):
var lists = u('li').map(function(node){ return node.parentNode });
.each() loop all the elements without changing them
Remove known nodes from nodes
.not('a')
.not(u('a'))
.not(function(node){ return Math.random() > 0.5; })
not
: it can be two things (in order):
- CSS selector that each of the nodes must not match to stay
- Instance of Umbrella with the element to remove
- Function that returns
true
to remove the element. It accepts one parameter, and the context ofthis
is the instance of Umbrella so methods likethis.slice()
are available
.not(function(node){
// your code
});
<ul class="menu">
<li><a class="active">Menu item 1</a></li>
<li><a>Menu item 2</a></li>
<li><a>Menu item 3</a></li>
</ul>
Get only the non-active links on paragraphs
var nonactive_links = u('.menu a').not('.active');
Get all of the active:
active_links = u('.menu a').not(nonactive_links);
.is() check whether one or more of the nodes is of one type
.filter() Remove unwanted nodes
Remove event handler from matched nodes
.off('event1')
.off('event1 event2 eventN')
.off('event1,event2,eventN')
.off(['event1', 'event2', 'eventN'])
.off('event1', callback)
.off('event1', 'selector', callback)
event1
, event2
, eventN
: the name(s) of the events to remove, such as click
, submit
, change
, etc.
selector
(optional): a CSS selector that matches the nodes that will trigger it. Use this only if the event was delegated, see .on()
for more info.
callback
(optional): the specific function to be removed. If this is left empty, all the functions associated with the event will be removed.
Umbrella instance
<ul>
<li class="off-single-test">1</li>
<li class="off-multiple-test">2</li>
<li class="off-multiple-test">3</li>
</ul>
const listener = function() {
alert('called');
}
//Add listener
u('.off-multiple-test').on('click', listener);
//Trigger event
u('.off-multiple-test').trigger('click'); //Alert appears
//Remove listener
u('.off-multiple-test').off('click', listener);
//Trigger event
u('.off-multiple-test').trigger('click'); //No alert
.on() Attaches an event to matched nodes
.handle() Same as .on()
, but it prevents the default action
.trigger() Triggers an event on all of the matched nodes
Calls a function when an event is triggered
.on('event1', callback)
.on('event1 event2 eventN', callback)
.on('event1,event2,eventN', callback)
.on(['event1', 'event2', 'eventN'], callback)
.on('event1', 'selector', callback)
event1
, event2
, eventN
: the name(s) of the events to listen for actions, such as click
, submit
, change
, etc.
callback
: function that will be called when the event is triggered. The parameters it accepts are function(e, data1, data2, ..., dataN)
:
-
e
: the event that was triggered. It has some interesting properties:e.currentTarget
: Contains the element that triggered the event.e.preventDefault()
: Avoids the browser from performing the default action.e.details
: an array of the argument data passed totrigger()
if it was passed with that function. See other arguments:
-
data1
,data2
,dataN
: the arguments that were passed totrigger()
if it was called with that function.
Another way is doing event delegation, for which the parameters are:
event1
, event2
, eventN
: same as before
selector
: a CSS selector that matches the nodes that will trigger it
callback
: same as before
Umbrella instance
An auto-save feature that submits the form through AJAX every 10 seconds
// Show 'test' when the button test is clicked
u('button.test').on('click', function(e) {
alert("Test");
});
// Submit a form through Ajax
u('form.test').on('submit', function(e){
// Avoid submitting the form normally
e.preventDefault();
// Submit the form through AJAX
fetch(u(this).attr('action'), { body: u(this).serialize(), ... });
});
// Better 'onchange':
u('input').on('change click blur paste', function(){
console.log("Maybe changed");
});
If you are modifying a bit of the DOM dynamically and want to attach events to it, a good way of doing it is with event delegation. For example, let's say we have the .render
class for rendering a bit of markdown to html, and we want to listen to any click to any link inside and intercept them. We could do u('.render a')
every time, or just do it once with delegation:
// Without event delegation, we are forced to add the event listeners every time
// we re-render the block of code
function renderHtml(plain) {
const content = sanitize(plainToHtml(plain));
u('.render').html(content);
u('.render a').on('click', function(node) {
alert('Clicked on ' + u(node).attr('href'));
});
}
// With event delegation, we can listen once for all clicks on links:
u('.render').on('click', 'a', function(node) {
alert('Clicked on ' + u(node).attr('href'));
});
// The above will listen to clicks on links even if the html changes dynamically
function renderHtml(plain) {
const content = sanitize(plainToHtml(plain));
u('.render').html(content);
}
With event delegation, e.currentTarget
might not work on all browsers as expected.
.handle() Same as .on()
, but it prevents the default action
.trigger() calls an event on all of the matched nodes
.off() Removes an event from matched nodes
Retrieve each parent of the matched nodes, optionally filtered by a selector
.parent()
.parent('p')
.parent(u('p'))
.parent(function(node, i){})
selector
: Optional filter argument for the parents
Retrieve all of the parents of <li>
in the page:
u('li').parent();
Retrieve all the paragraphs that have a link as a direct child
u('a').parent('p');
.children() get all of the direct children
.find() get all of the descendants of the matched nodes
.closest() get the first ascendant that matches the selector
Add some html as a child at the beginning of each of the matched elements.
.prepend(html)
.prepend('<div>')
.prepend(u('<div>'))
.prepend(u('<div>').first()) // Same as document.createElement('div')
.prepend(u('<div></div><div></div>').nodes)
.prepend(function(){})
.prepend(function(el){}, elements)
.prepend(function(el){}, 10)
html = ""
:
- Any of these elements:
- string containing the html that is going to be inserted
- instance of Umbrella
- HTML node
- array containing HTML nodes
- A callback that returns any of the previous. It gets passed these parameters:
- el: the current element from the elements parameter, {} if none is specified and i if elements is number
- i: the index of the current element
elements = [{}]
(optional): It can be any of the following:
- An array of elements that will be passed to the callback. The callback is executed once per element, and all of them are added consecutively.
- A CSS selector, so the function will be executed once per matched element.
- A number, in which case the function will be executed that number of times
u
: returns the same instance of Umbrella JS
Add a header to each of the articles
u("article").prepend("<header>Hello world</header>");
Add three elements at the beginning of the list. All of these methods are equivalent:
// Add them all like a single string
u("ul").prepend("<li>One</li><li>Two</li><li>Three</li>");
// Add them in a chain
u("ul").prepend("<li>Three</li>").append("<li>Two</li>").append("<li>One</li>");
// Add them with a function parameter
var cb = function(txt){ return "<li>" + txt + "</li>" };
u("ul").prepend(cb, ["One", "Two", "Three"]);
// Same as the previous one but with ES6
u("ul").prepend(txt => `<li>${ txt }</li>`, ["One", "Two", "Three"]);
They all result in:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<!-- previous data -->
</ul>
You can also add some events to them by creating an html node:
function greeting(){ alert("Hello world"); }
u("a.main").prepend(function(){
return u('<a>').addClass('hi').on('click', greeting).html("Greetings!");
});
.append() Add some html as a child at the end of each of the matched elements
.before() Add some html before each of the matched elements.
.after() Add some html as a sibling after each of the matched elements.
Removes the matched elements.
.remove();
This method doesn't accept any parameters
u
: Returns an instance of Umbrella JS with the removed nodes.
Remove all the elements of a list:
u("ul.demo li").remove();
Remove html class(es) to all of the matched elements.
.removeClass('name1');
.removeClass('name1 name2 nameN');
.removeClass('name1,name2,nameN');
.removeClass('name1', 'name2', 'nameN');
.removeClass(['name1', 'name2', 'nameN']);
.removeClass(['name1', 'name2'], ['name3'], ['nameN']);
.removeClass(function(){ return 'name1'; });
.removeClass(function(){ return 'name1'; }, function(){ return 'name2'; });
name1
, name2
, nameN
: the class name (or variable containing it) to be removed to all of the matched elements. It accepts many different types of parameters (see above).
u
: returns the same instance of Umbrella JS
Remove the class main
to all the <h2>
from the page:
u("h2").removeClass("main");
Remove the class toValidate
and ajaxify
to all the <form>
present in the page:
u("form").removeClass("toValidate", "ajaxify");
.addClass() adds class(es) from the matched elements.
.hasClass() finds if the matched elements contain the class(es)
Replace the matched elements with the passed argument.
.replace();
The parameter can be any of these types:
- string: html tag like
<div>
- function: a function which returns an html tag.
The newly created element.
Replace elements with class 'save' by a button with class 'update':
u('.save').replace('<button class="update">Update</button>');
Replace element button by a link with class 'button':
u('button').replace(function(btn){
return '<a class="button">' + btn.innerHTML + '</a>';
});
Scroll to the first matched element, smoothly if supported.
.scroll()
Scroll to the first <li>
in the page:
u('li').scroll();
On click event, scroll the first <section>
element with the class "team":
u('a.team').on('click', function(e){
e.preventDefault();
u('section.team').scroll();
});
Note: you probably want to use the native
FormData()
instead of.serialize()
. See relevant issue.
Converts a form into a string to be sent:
.serialize()
Note: multiple-select are not supported in Internet Explorer, similarly to jQuery
For this form:
<form action="/contact" method="POST">
Email:
<input type="email" name="email" value="[email protected]" />
Message:
<textarea type="email" name="message">Hello world</textarea>
<button>Send</button>
</form>
When the user clicks on the "Send" button, the following handler can be used to send the data through Ajax:
// .handle() == .on() + preventDefault()
u('form.contact').handle('submit', async e => {
// Body: [email protected]&message=Hello+world
const body = u(e.target).serialize();
const data = await fetch('/contact', {
method: 'POST', body
}).then(res => res.json());
console.log('Response data:', data);
});
If you were using the native FormData:
// .handle() == .on() + preventDefault()
u('form.contact').handle('submit', async e => {
const body = new FormData(e.target);
const data = await fetch('/contact', {
method: 'POST', body
}).then(res => res.json());
console.log('Response data:', data);
});
Get the siblings of all of the nodes with an optional filter
.siblings(selector);
selector
: a string containing a selector that nodes must pass or a function that return a boolean. See .filter() for a better explanation
u
: returns an instance of Umbrella JS with the new siblings as nodes
Get the all the siblings of the hovered <li>
u("li:hover").siblings('li:first-child');
Get all the siblings
u("li").siblings();
.parent() get all of the direct parents
.find() get all of the descendants of the matched nodes
.closest() get the first ascendant that matches the selector
.children() get the direct children of all of the nodes with an optional filter
Get the bounding client rect of the first matched element. This has height, width, top, left, right and bottom properties
.size()
None
Returns a simple object with the following properties referring to the first matched element, or null
if there is no one:
- left
- right
- top
- height
- bottom
- width
u('body').size();
// {"left":0,"right":400,"top":0,"height":300,"bottom":300,"width":400}
u().size()
// null
Retrieve or set the text content of matched elements:
// GET
.text();
// SET
.text(text);
GET should pass no parameter so it retrieves the text from the first matched element.
SET
html
: the new text content that you want to set for all of the matched elements. To remove it, pass an empty string: ""
GET
string
: the text content of the first matched element
SET
u
: returns the same instance of Umbrella JS
Get the main title text:
var title = u('h1').text();
Set the main title text:
u('h1').text('Hello world');
.html() Retrieve or set the HTML of matched elements
Toggles html class(es) to all of the matched elements.
.toggleClass('name1');
.toggleClass('name1 name2 nameN');
.toggleClass('name1,name2,nameN');
.toggleClass(['name1', 'name2', 'nameN']);
.toggleClass('name1', forceAdd);
name1
, name2
, nameN
: the class name (or variable containing it) to be toggled to all of the matched elements. It accepts many different types of parameters (see above).
forceAdd
: boolean telling the method whether to force an .addClass()
(true) or .removeClass()
(false).
u
: returns the same instance of Umbrella JS
Add the class main
to all the <h2>
from the page:
u("h2").toggleClass("main");
Add the class toValidate
and remove ajaxify
from the element <form class="ajaxify">
present in the page:
u("form.ajaxify").toggleClass("toValidate ajaxify");
Force an .addClass()
on the element <h2>
from the page:
u("h2").toggleClass("main", true);
Note however that this last example by itself doesn't make much sense as you could just use addClass()
instead. It makes a lot more sense when the second parameter is checked dynamically:
u("h2").toggleClass("main", u('.accept').is(':checked'));
.addClass() adds class(es) from the matched elements.
.removeClass() deletes class(es) from the matched elements.
.hasClass() finds if the matched elements contain the class(es)
Calls an event on all of the matched nodes
.trigger('event1', data)
.trigger('event1 event2 eventN', data1, data2, dataN)
.trigger('event1,event2,eventN', data1, data2, dataN)
.trigger(['event1', 'event2', 'eventN'], data1, data2, dataN)
event1
, event2
, eventN
: the name(s) of the events to listen for actions, such as click
, submit
, change
, etc.
data1
, data2
, dataN
(optional): the data that will be passed to the event listener in the e.details
variable and as arguments.
Umbrella instance
An auto-save feature that submits the form through AJAX every 10 seconds
// Submit it every 10s
setInterval(function(){
u('button.save').trigger('click');
}, 10000);
.on() add an event listener to the matched nodes
.handle() Same as .on()
, but it prevents the default action
.off() Removes an event from matched nodes
Wraps the matched element(s) with the passed argument. The argument gets processed with the constructor u() and it accepts an html tag like .wrap('<div>')
.wrap(selector);
selector
: a formatted string of the desired selector. For example .wrap('<div>')
. Nested selectors are supported in a similar way to jQuery wrap. For example .wrap('<div class="a1"><div class="b1"><div class="c1"></div></div></div>')
. Matched element(s) will be wrapped with innermost node of the first child of a nested argument. See examples below.
u
: returns an instance of Umbrella JS with the wrapped node(s)
Wrap an element in an html element:
Original element:
<span class="example">Link1</span>
u(".example").wrap('<a class="wrapper">');
Result:
<a class="wrapper">
<span class="example">Link1</span>
</a>
Wrap an element in an html element and chain Umbrella methods:
u(".example").wrap('<a>').attr({class: "wrapper", href: "http://google.com"});
Result:
<a href="http://google.com" class="wrapper">
<span class="example">Link1</span>
</a>
Wrap several elements in an html element
<span class="example">Link1</span>
<span class="example">Link2</span>
<span class="example">Link3</span>
u(".example").wrap('<a>').attr({class: "wrapper", href: "http://google.com"});
Result:
<a href="http://google.com" class="wrapper">
<span class="example">Link1</span>
</a>
<a href="http://google.com" class="wrapper">
<span class="example">Link2</span>
</a>
<a href="http://google.com" class="wrapper">
<span class="example">Link3</span>
</a>
Nested selector arguments:
<span class="example">Link1</span>
u(".example").wrap('<div class="a1"><div class="b1"><div class="c1"></div></div></div>');
Result:
<div class="a1">
<div class="b1">
<div class="c1">
<a href="http://google.com" class="wrapper">
<span class="example">Link1</span>
</a>
</div>
</div>
</div>
Nested selector arguments with multiple child nodes:
<span class="example">Link1</span>
u(".example").wrap('<div class="a1"><div class="b1"><div class="c1"></div></div><div class="b2"><div class="c2"><div class="d1"></div></div></div></div>');
Result:
<div class="a1">
<div class="b1">
<div class="c1">
<a href="http://google.com" class="wrapper">
<span class="example">Link1</span>
</a>
</div>
</div>
<div class="b2">
<div class="c2">
<div class="d1"></div>
</div>
</div>
</div>