0% found this document useful (0 votes)
31 views29 pages

IT Notes - in

This document discusses ES6 features including let and const declarations, arrow functions, template literals, destructuring, default parameters, rest parameters, and spread syntax. It provides examples and explanations of each feature.

Uploaded by

Priyanka S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views29 pages

IT Notes - in

This document discusses ES6 features including let and const declarations, arrow functions, template literals, destructuring, default parameters, rest parameters, and spread syntax. It provides examples and explanations of each feature.

Uploaded by

Priyanka S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

MODULE 4

ECMA Script: ECMA Script versions, ES5 Features, ES6 introduction, Var Declarations and
Hoisting, let declaration, Constant declaration, function with default parameter values, default
parameter expressions, unnamed parameters, the spread operator, arrow functions, object
destructuring, array destructuring, sets and maps, Array.find(), Array.findIndex(), template strings,
Javascript classes, callbacks, promises, async/await

ECMAScript 6 (ES6)

ES6 Variables
var vs let

Traditionally the keyword var initializes the identifier with a value:

var my_variable = 'value';


//1 //2 //3

//1 the var keyword


//2 the identifier
//3 the value

There are rules for naming the variable identifier. These are:

 identifiers cannot be keywords


 can be alphanumeric, although cannot start with a number
 $ and _ are also allowed characters for an identifier

Variables decalred by var have the scope of the entire function.

function myFunc() {
if(true) {
var my_var = 'test';
}
console.log(my_var); // test
}

The let keyword

Downloaded from Ktunotes.in


let is preferred over var. Variables decalred by let have their scope
within the block they are defined.

function myFunc() {
if(true) {
let my_var = 'test';
}
console.log(my_var); // TypeError
}

Block scoping allows for variable shadowing.

function myFunc() {
let my_var = 'test';
if(true) {
let my_var = 'new test';
console.log(my_var); // new test
}
console.log(my_var); // test
}

The const keyword


ES6 also introduced a new variable keyword: const. Variables declared with the const keyword
are block scoped just like let however they cannot change by reassignment and they cannot be re-
declared; they are immutable.

const version = '0.0.1';


version = '0.0.2'; // TypeError: invalid assignment to const

const name = 'bill';


const name = 'ted'; // SyntaxError: Identifier 'name' has already been declared

Variables declared by const (constants) cannot be changed. However, with a for loop the scope is
redeclared at the start of each loop, where a new const can be initalized.

ES6 for/of
The for/of loop uses the iterable protocol to create a loop. Strings, Arrays, TypedArray, Map,
Set, NodeList, and custom iterable function hooks can all be used with for/of.

const arr = [1, 2, 3];

Downloaded from Ktunotes.in


for(const number of arr) {

console.log(number) // 1 2 3

ES6 Template Literals


ES6 introduced a new syntax for strings called “template string”s or “template literals.”
Template strings are not just a cool new way to write strings. They come with new features as
well.

Let’s take a look at the ES5 string and refactor it using a template literal.

// ES5 string
let myName = 'Tony Nguyen'

To create a template literal, just use the backtick(`) character instead of the single or double
quotes. The backtick the same key as the ~ key usually below the escape key.

// ES6 template string


let myName = Tony Nguyen

It really is that simple. Now that you know how to write a template string let’s take a look at
some of the things you can do with template strings.

Template literals are very handy for strings that use variables, or need to make use of a quick
javascript expression. Template literals are enclosed with the back-tick. Template literals can
also have placeholders,these are declared with a dollar sign and curly braces ${placeholder}.

const number = 42;


const str = `Here's my favourite number: ${number}.`;
console.log(str) // Here's my favourite number: 42.

const count = 0;
console.log(`${count + 1}`); // 1

Downloaded from Ktunotes.in


Template literals can be tagged with a function identifier before the back-ticks. The function
allows you to parse the template literal. The first argument is an array of string values, the rest of
the arguments relate to the placeholders in the template literal.

ES6 Arrow Functions


Arrow functions are a shorthand syntax for functions that do not contain its
own this, arguments, super, or new.target and cannot be used as
constructors.

const arr = ['hammer', 'nails', 'pizza', 'test'];


console.log(arr.map(value => value.length)); // [6, 5, 5, 4]

Arrow functions are useful for anonymous functions, however their power is with the lexical
scoping of this.

function es6LexicalScope() {
this.timeSpentSeconds = 0;
setInterval(() => {
console.log(this.timeSpentSeconds++); // 1 2 3 ...
}, 1000);
}
es6LexicalScope();

Arrow functions do not have a prototype.

const func = () => {};


console.log(func.prototype); // undefined

To return an object as an implicit return, you can wrap the object in


the grouping operator (parentheses).

const returnObjBad = () => { test: 'value' };


console.log(returnObj); // undefined

const returnObjGood = () => ({test: 'value'});


console.log(returnObj); // { test: 'value' }

If you noticed, there is a small difference between the usage of arrow


functions in the provided exmaples. The usage of ():

 Arrow functions with no parameters require ()


 Arrow functions with one parmeter () are optional
 Arrow functions with two or more parameters require ()
 Arrow functions that only return, do not need {}, return, or ;
const fn1 = () => {[Native Code]};

Downloaded from Ktunotes.in


const fn2 = param => {[Native Code]};
const fn2a = (param) => {[Native Code]};
const fn3 = (param1, param2) => {[Native Code]};
const fn4 = param => param;

ES6 Destructuring Assignment


Destructuring assignment lets you unpack values from an array or object.

const [x, y] = [1, 2, 3, 4, 5];


console.log(x); // 1
console.log(y); // 2;

const person = { name: 'Bill', age: 42, email: '[email protected]', url: 'http://example.ca' };
const {name, age} = person;
console.log(name, age); // Bill, 42

Sometimes you want to keep all the other stuff. That is where the spread operator ... comes in
handy.

const [x, y, ...allTheRest] = [1, 2, 3, 4, 5];


console.log(x, y, allTheRest); // 1, 2, [3, 4, 5]

const person = { name: 'Bill', age: 42, email: '[email protected]', url: 'http://example.ca' };
const {name, age, ...details} = person;
console.log(name, age, details); // Bill, 42, {email: '[email protected]', url: 'http://example.ca'}

You can also destructure to build new variables!

const otherObj = {};


const person = { name: 'Bill', age: 42, email: '[email protected]', url: 'http://example.ca' };
const obj = {...otherObj, person};
console.log(obj); // { person: {[...]} }

obj now has our person property with our person Bill. If the person
property was already set in otherObj then we would override that property. Let's look at
unpacking the length property from a string with destructuring.

const arr = ['hammer', 'nails', 'pizza', 'test'];


// without destructuring
console.log(arr.map(value => value.length)); // [6, 5, 5, 4]
// with destructuring
console.log(arr.map(({ length }) => length)); // [6, 5, 5, 4]

Downloaded from Ktunotes.in


Let's breakdown the line we just added. console.log(arr.map( is pretty
standard. ({ length }) is the parameter for our arrow function, we are passing in a string and
destructuring the length property from the string and passing that as a variable called length. The
function parameter is the string length. => length)); the rest of our arrow function. The property
is also the variable identifier and we only return the length. If you need a default with
destructuring, you can do that too!

const { name = 'Bill', age = 30 } = { name: 'Ted' };


console.log(name, age)// Ted, 30

const [x = 5, y = 10] = [20];


console.log(x, y) // 20, 10

Spread Operator
Spread syntax (...) allows an iterable such as an array expression or string to be expanded in
places where zero or more arguments (for function calls) or elements (for array literals) are
expected, or an object expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.

function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6

Spread syntax can be used when all elements from an object or array need to be included in a list
of some kind.

In the above example, the defined function takes x, y, and z as arguments and returns the sum of
these values. An array value is also defined.

When we invoke the function, we pass it all the values in the array using the spread syntax and
the array name — ...numbers.

Downloaded from Ktunotes.in


If the array contained more than three numbers, e.g. [1, 2, 3, 4], then it would still work fine,
except that all four would be passed, but only the first three would be used unless you added
more arguments to the function, e.g.:

Rest parameters
The rest parameter syntax allows a function to accept an indefinite number of arguments as an
array, providing a way to represent variadic functions in JavaScript.

function sum(...theArgs) {

return theArgs.reduce((previous, current) => {

return previous + current;

});

console.log(sum(1, 2, 3));

// expected output: 6

console.log(sum(1, 2, 3, 4));

// expected output: 10

ES6 Default Parameters


Funtions accept default parameters and destructuring parameters.

function addToFive(addTo = 0) {
return addTo + 5;
}
const ex1 = addToFive();
const ex2 = addToFive(5);
console.log(ex1, ex2); // 5, 10

function fullname ({firstname, lastname}) {


return `${firstname lastname}`;
}
const user = { firstname: 'Theodore', lastname: 'Logan', age: '20' };
const fullname = fullname(user);

Downloaded from Ktunotes.in


console.log(`Hello ${fullname}`);

When destructuring you can also assign defaults.

function myFunc({age = 42}) {


console.log(age); // 42
};
myFunc({name: 'Theodor'});

Maps And Sets

JavaScript sets and maps have been around for a few years now, but I still get a lot of questions
about them. My students wonder if they should be substituting traditional objects and arrays with
these new data types. While there are some killer use cases for sets and maps, you should really
look at them like specialized tools and not Swiss army knives.

When to use sets


A Set is a collection, like an array, except each value must be unique. They’re like what would
happen if objects and arrays had a baby. Here’s a crash course:

const mySet = new Set();

mySet.add(1); // add item


mySet.add('a');
mySet.size; // 2
mySet.delete(1)
mySet.has(1); // false
mySet.clear(); // empties set

You need to remove duplicates


This is probably the only time I’ve actually seen sets used in the wild. It’s a handy one liner:

const arr = [1,2,3,4,4,5,6,7,7,7]


const unique = [...new Set(arr)]
// unique equals [1,2,3,4,5,6,7]

When to use maps


Maps are honestly something that I personally thought would take over the landscape. But, then
when you get down to it, they’re not as much of an upgrade as you might think. They are another

Downloaded from Ktunotes.in


way to store key/value data, but they’re more purpose-driven than objects, so they have some
added benefits. Here’s a crash course:

const myMap = new Map();


myMap.set('a', 1);
myMap.set('b', 2);
myMap.set('c', 3);
myMap.get('a'); // 1
myMap.set('a', 'ok');
myMap.get('a'); // 'ok'
myMap.size; // 3
myMap.delete('b'); // removes b key/value
myMap.clear() // empties map

Arrays, Array.find(), Array.findIndex()


If we talk in programming language, an array is said to be a collection of elements or items. They
store data as elements and can retrieve them back whenever you need them. It is a widely used
data structure in the programming languages that support it.
In JavaScript, we can use a pair of square brackets [] to represent an array. Every single element
in the array is separated by a comma(,). They can be a collection of elements of any data type,
meaning that you can create an array with elements of data type String, Boolean, Number,
Objects, and even other Arrays. They are used to store multiple values in a single variable.

Array.find()
This method returns the value of the first element in the provided array that satisfies the provided
testing function. If no values satisfy the testing function, undefined is returned.

Example:

const arrayA = [7, 12, 8, 140, 54];

const found = arrayA.find(element => element > 10);

console.log(found);
// output: 12

Different Array Methods


1. Array.push()
2. Array.unshift()
3. Array.pop()
4. Array.shift()
5. Array.splice()

Downloaded from Ktunotes.in


6. Array.concat()
7. Array.isArray()
8. Array.slice()
9. Array.length
10. Array.includes()
11. Array.from()
12. Array.fill()
13. Array.filter()
14. Array.find()
15. Array.forEach()
16. Array.map()
17. Array.flat()
18. Array.reverse()
19. Array.every()
20. Array.copyWithin()
21. Array.reduce()
22. Array.flatMap()
23. Array.some()
24. Array.of()
25. Array.sort()
26. Array.join()
27. Array.toLocaleString()
28. Array.keys()
29. Array.values()
30. Array.entries(

Promises in JavaScript

There are two parts to understanding promises. Creation of promises and Handling of
promises. Though most of our code will generally cater to handling of promises created by other
libraries, a complete understanding will help us for sure. Understanding of “creation of
promises” is equally important once you cross the beginner stage.

Creation of Promises

Let us look at the signature for creating a new promise.

The constructor accepts a function called executor. This executor function


accepts two parameters resolve and reject which are in turn functions.
Promises are generally used for easier handling of asynchronous operations or
blocking code, examples for which being file operations, API calls, DB calls, IO
calls etc.The initiation of these asynchronous operations happens within the

Downloaded from Ktunotes.in


executorfunction. If the asynchronous operations are successful then the
expected result is returned by calling the resolvefunction by the creator of
the promise. Similarly if there was some unexpected error the reasons is passed
on by calling the rejectfunction.

Now that we know how to create a promise. Let us create a simple promise for our
understanding sake.

var keepsHisWord;
keepsHisWord = true;
promise1 = new Promise(function(resolve, reject) {
if (keepsHisWord) {
resolve("The man likes to keep his word");
} else {
reject("The man doesnt want to keep his word");
}
});
console.log(promise1);

Every promise has a state and value

Since this promise gets resolved right away we will not be able to inspect the
initial state of the promise. So let us just create a new promise that will take
some time to resolve. The easiest way for that is to use the setTimeOut
function.

promise2 = new Promise(function(resolve, reject) {


setTimeout(function() {
resolve({
message: "The man likes to keep his word",
code: "aManKeepsHisWord"
});
}, 10 * 1000);
});
console.log(promise2);

The above code just creates a promise that will resolve unconditionally after 10
seconds. So we can checkout the state of the promise until it is resolved.

Downloaded from Ktunotes.in


Promises , Callbacks and Async/Await

Promises,callbacks and async/await are all ways to deal with asynchronous data.Basically
asynchronous is when something is going on but you don't want to wait till its done to
continue,and you want to continue while it's happening asynchronously rather than synchronous
programming where something happens where you wait till it finishes to move on to the next.

Asynchronous programming is very essential to javascript as we often make requests to servers


and other places where it can take a few seconds to obtain the data from and if we don't want our
program to stall and wait around at these situations,this is where callbacks come in.

With the introduction of ES6 promises were introduced to the language.Promises provide us with
a more elegant way to handle asynchronous data.

In ES7,async/await were introduced which deals with promises in an even more elegant way as it
looks more like synchronous programming.

Callbacks
A callback is a function passed as an argument to another function.This technique allows a
function to call another function.A callback function can run after another function has finished

Let us consider a hypothetical situation where we get posts and create post from a server.Lets use
a setTimeout to mimic the time lapse given by the server.

Lets have an array called posts that contains two objects and create a function called getPosts

const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
];

function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}

getPosts();

Downloaded from Ktunotes.in


The titles are loaded after a second.

Now lets write a createPost function.

const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
];

function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}

function createPost(post){
setTimeout(()=> {
posts.push(post);
},2000);
}

getPosts();

createPost({title:'Post Three',body:'This is post three'});

But now we don't see the post three because the create post took longer than the getPost which
happened in 1 second and by the time post was created the DOM was already painted.

This is where asynchronous programming comes in.Callbacks are one of the ways to do handle
this.

Now lets have the createPost also take in a function called callback and call the callback() right
after the post is pushed.

Now all we have to do is make the getPosts function the callback.

Downloaded from Ktunotes.in


const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
];

function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}

function createPost(post,callback){
setTimeout(()=> {
posts.push(post);
callback();
},2000);
}

createPost({title:'Post Three',body:'This is post three'},getPosts);

Now it will wait 2 seconds and call the entire posts array.

This is a simple implementation to understand how a callback would work.

Promises
A Promise is a proxy for a value not necessarily known when the promise is created. It allows
you to associate handlers with an asynchronous action's eventual success value or failure reason.
This lets asynchronous methods return values like synchronous methods: instead of immediately
returning the final value, the asynchronous method returns a promise to supply the value at some
point in the future.

Considering the same example lets use the same array and getPost function.

But now instead of using a callback to handle the createPost lets use a promise.

const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}

Downloaded from Ktunotes.in


];

function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}

function createPost(post){
return new Promise((resolve,reject) => {
setTimeout(()=> {
posts.push(post);

const error = false;

if(!error) {
resolve();
} else {
reject('Error:Something is wrong');
}
},2000);
});
}

createPost({title:'Post Three',body:'This is post three'})


.then(getPosts)
.catch(err => console.log(err));

Here instead of running the callback we return a promise.

A promise takes in two parameters :

 resolve
 reject

When we want to resolve a promise a successfully,we will call the resolve and when something
goes wrong or if there is an error we will call reject.

Now we are not going to pass a callback function and since its returning a promise we will
handle it using .then.

Downloaded from Ktunotes.in


This time running it will wait for the timeout and as soon as its done it resolves and once it
resolves then it will call the getPosts.

The .catch that is used after the .then is used for error handling if the promise is rejected.

There will be a lot of instances where we might have to deal with promises like when we use
axios,fetch,mongoose..etc and most of the time we will just be required to respond to the promise
but the above code is a good example on how to create a promise yourself.

Lets take a look at Promise.all

Consider the following promises:

//Promise.all

const promise1 = Promise.resolve('Hello World');


const promise2 = 10;
const promise3 = new Promise((resolve,reject) => setTimeout(resolve,2000,'Goodbye!')
);

Promise.all([promise1,promise2,promise3]).then(values => console.log(values));

The promise.all will return after all the promises are done and it will take time until the longest
promise is handled.

Async/Await
These features basically act as syntactic sugar on top of promises, making asynchronous code
easier to write and to read afterwards. They make async code look more like old-school
synchronous code, so they're well worth learning.

The keyword async before a function makes the function return a promise.The keyword await
before a function makes the function wait for a promise.The await keyword can only be used
inside an async function.

Place the createPost function inside a new function and prefix the async keyword to the function
which will make it asynchronous and before calling createPost prefix it with await and call the
getPosts below it.

const posts=[
{title:'Post One',body:'This is post one'},
{title:'Post Two',body:'This is post two'}
];

Downloaded from Ktunotes.in


function getPosts() {
setTimeout(()=> {
let output = '';
posts.forEach((post,index)=> {
output += `<li>${post.title}</li>`;
});
document.body.innerHTML = output;
},1000);
}

function createPost(post){
setTimeout(()=> {
posts.push(post);
},2000);
}

async function init() {


await createPost({title:'Post Three',body:'This is post three'});
getPosts();

init()

When the init function is called,the await waits till the process is done and once completed it will
move to the next and call the getPosts function.

Downloaded from Ktunotes.in


JQuery : What is JQuery ?, A basic JQuery example, Why use JQuery ?, finding
elements, JQuery selection, getting element content, updating elements, changing
content, inserting elements, adding new content, getting and setting attributes,
getting and setting CSS properties, using .each(), events, event object, effects,
animating CSS properties, using animation, traversing the DOM, working with
forms, JavaScript libraries, JQuery and ajax

What is jQuery?
jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish,
and wraps them into methods that you can call with a single line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.

The jQuery library contains the following features:

 HTML/DOM manipulation
 CSS manipulation
 HTML event methods
 Effects and animations
 AJAX
 Utilities

jQuery Syntax
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).

Basic syntax is: $(selector).action()

 A $ sign to define/access jQuery


 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

Downloaded from Ktunotes.in


$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

jQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes,
types, attributes, values of attributes and much more. It's based on the existing CSS Selectors,
and in addition, it has some own custom selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector

The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

Example

When a user clicks on a button, all <p> elements will be hidden:

$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.

To find an element with a specific id, write a hash character, followed by the id of the HTML
element:

$("#test")

Downloaded from Ktunotes.in


Example

When a user clicks on a button, the element with id="test" will be hidden:

$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

Moving, Copying, and Removing Elements


While there are a variety of ways to move elements around the DOM, there are generally two
approaches:

 Place the selected element(s) relative to another element.


 Place an element relative to the selected element(s).

For example, jQuery provides .insertAfter() and .after(). The .insertAfter() method places the
selected element(s) after the element provided as an argument. The .after() method places the
element provided as an argument after the selected element. Several other methods follow this
pattern: .insertBefore() and .before(), .appendTo() and .append(),
and .prependTo() and .prepend().

The method that makes the most sense will depend on what elements are selected, and whether
you need to store a reference to the elements you're adding to the page. If you need to store a
reference, you will always want to take the first approach – placing the selected elements relative
to another element – as it returns the element(s) you're placing. In this
case, .insertAfter(), .insertBefore(), .appendTo(), and .prependTo() should be the tools of choice.

// Moving elements using different approaches.

// Make the first list item the last list item:

var li = $( "#myList li:first" ).appendTo( "#myList" );

// Another approach to the same problem:

$( "#myList" ).append( $( "#myList li:first" ) );

// Note that there's no way to access the list item

Downloaded from Ktunotes.in


// that we moved, as this returns the list itself.

Cloning Elements
Methods such as .appendTo() move the element, but sometimes a copy of the element is needed
instead. In this case, use .clone() first:

// Making a copy of an element.

// Copy the first list item to the end of the list:


$( "#myList li:first" ).clone().appendTo( "#myList" );
If you need to copy related data and events, be sure to pass true as an argument to .clone().

Creating New Elements


jQuery offers a trivial and elegant way to create new elements using the same $() method used to
make selections:

// Creating new elements from an HTML string.


$( "<p>This is a new paragraph</p>" );
$( "<li class=\"new\">new list item</li>" );

// Creating a new element with an attribute object.


$( "<a/>", {
html: "This is a <strong>new</strong> link",
"class": "new",
href: "foo.html"
});
Note that the attributes object in the second argument above, the property name class is quoted,
although the property names html and href are not. Property names generally do not need to be
quoted unless they are reserved words (as class is in this case).

When you create a new element, it is not immediately added to the page. There are several ways
to add an element to the page once it's been created.

// Getting a new element on to the page.

var myNewElement = $( "<p>New element</p>" );

myNewElement.appendTo( "#content" );

myNewElement.insertAfter( "ul:last" ); // This will remove the p from #content!

$( "ul" ).last().after( myNewElement.clone() ); // Clone the p so now we have two.

Downloaded from Ktunotes.in


The created element doesn't need to be stored in a variable – you can call the method to add the
element to the page directly after the $(). However, most of the time you'll want a reference to
the element you added so you won't have to select it later.

You can also create an element as you're adding it to the page, but note that in this case you don't
get a reference to the newly created element:

1
// Creating and adding an element to the page at the same time.
$( "ul" ).append( "<li>list item</li>" );
2

The syntax for adding new elements to the page is easy, so it's tempting to forget that there's a
huge performance cost for adding to the DOM repeatedly. If you're adding many elements to the
same container, you'll want to concatenate all the HTML into a single string, and then append
that string to the container instead of appending the elements one at a time. Use an array to
gather all the pieces together, then join them into a single string for appending:

3 var myItems = [];


var myList = $( "#myList" );
4
for ( var i = 0; i < 100; i++ ) {
myItems.push( "<li>item " + i + "</li>" );
5
}
6 myList.append( myItems.join( "" ) );
7

Manipulating Attributes
jQuery's attribute manipulation capabilities are extensive. Basic changes are simple, but
the .attr() method also allows for more complex manipulations. It can either set an explicit value,
or set a value using the return value of a function. When the function syntax is used, the function
receives two arguments: the zero-based index of the element whose attribute is being changed,
and the current value of the attribute being changed.

Downloaded from Ktunotes.in


// Manipulating a single attribute.
$( "#myDiv a:first" ).attr( "href", "newDestination.html" );

// Manipulating multiple attributes.


$( "#myDiv a:first" ).attr({
href: "newDestination.html",
rel: "nofollow"
});

// Using a function to determine an attribute's new value.


$( "#myDiv a:first" ).attr({
rel: "nofollow",
href: function( idx, href ) {
return "/new/" + href;
}
});

$( "#myDiv a:first" ).attr( "href", function( idx, href ) {


return "/new/" + href;
});

.each()

The .each() method is designed to make DOM looping constructs concise and less error-prone.
When called it iterates over the DOM elements that are part of the jQuery object. Each time the
callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the
callback is fired in the context of the current DOM element, so the keyword this refers to the
element.

Suppose you have a simple unordered list on the page:

<ul>
<li>foo</li>
<li>bar</li>
</ul>
You can select the list items and iterate across them:

$( "li" ).each(function( index ) {


console.log( index + ": " + $( this ).text() );
});
A message is thus logged for each item in the list:

Downloaded from Ktunotes.in


0: foo
1: bar

You can stop the loop from within the callback function by returning false.

These methods get and set DOM attributes of elements.

These methods get and set DOM attributes of elements.

.addClass()
Adds the specified class(es) to each element in the set of matched elements.

.attr()
Get the value of an attribute for the first element in the set of matched elements or set one or
more attributes for every matched element.

.hasClass()
Determine whether any of the matched elements are assigned the given class.

.html()
Get the HTML contents of the first element in the set of matched elements or set the HTML
contents of every matched element.

.prop()
Get the value of a property for the first element in the set of matched elements or set one or more
properties for every matched element.

.removeAttr()
Remove an attribute from each element in the set of matched elements.

.removeClass()
Remove a single class, multiple classes, or all classes from each element in the set of matched
elements.

.removeProp()
Remove a property for the set of matched elements.

Events
These methods are used to register behaviors to take effect when the user interacts with the
browser, and to further manipulate those registered behaviors.

Downloaded from Ktunotes.in


These methods are used to register behaviors to take effect when the user interacts with the
browser, and to further manipulate those registered behaviors.

.bind()
Attach a handler to an event for the elements.

.blur()
Bind an event handler to the “blur” JavaScript event, or trigger that event on an element.

.change()
Bind an event handler to the “change” JavaScript event, or trigger that event on an element.

.click()
Bind an event handler to the “click” JavaScript event, or trigger that event on an element.

events, event object,

o Browser Events
o Document Loading
o Event Handler Attachment
o Event Object
o Form Events
o Keyboard Events
o Mouse Events

.unbind( eventType [, handler ] )

eventType

Type: String

A string containing one or more DOM event types, such as "click" or "submit," or custom event
names.

handler

Type: Function( Event eventObject )


The function that is to be no longer executed.

Annimating CSS properties

Downloaded from Ktunotes.in


The $.cssHooks object provides a way to define functions for getting and setting particular CSS
values. It can also be used to create new cssHooks for normalizing CSS3 features such as box
shadows and gradients.

For example, some versions of Webkit-based browsers require -webkit-border-radius to set


the border-radius on an element, while earlier Firefox versions require -moz-border-radius. A css
hook can normalize these vendor-prefixed properties to let .css() accept a single, standard
property name (border-radius, or with DOM property syntax, borderRadius).

In addition to providing fine-grained control over how specific style properties are
handled, $.cssHooks also extends the set of properties available to the .animate() method.

Defining a new css hook is straight-forward. The skeleton template below can serve as a guide to
creating your own.

(function( $ ) {

// First, check to see if cssHooks are supported

if ( !$.cssHooks ) {

// If not, output an error message

throw( new Error( "jQuery 1.4.3 or above is required for this plugin to work" ) );

// Wrap in a document ready call, because jQuery writes

// cssHooks at this time and will blow away your functions

// if they exist.

$(function () {

$.cssHooks[ "someCSSProp" ] = {

get: function( elem, computed, extra ) {

// Handle getting the CSS property

Downloaded from Ktunotes.in


},

set: function( elem, value ) {

// Handle setting the CSS value

};

});

})( jQuery );

Traversing the DOM


Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to
search through the immediate children of these elements in the DOM tree and construct a new
jQuery object from the matching elements. The .contents() and .children() methods are similar,
except that the former includes text nodes and comment nodes as well as HTML elements in the
resulting jQuery object. Please note that most jQuery operations don't support text nodes and
comment nodes. The few that do will have an explicit note on their API documentation page.

The .contents() method can also be used to get the content document of an iframe, if the iframe is
on the same domain as the main page.

As of jQuery 3.2, .contents() returns contents of <template> elements as well.

Consider a simple <div> with a number of text nodes, each of which is separated by two line
break elements (<br>):

<div class="container">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
<br><br>
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
<br><br>
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur.
</div>
We can employ the .contents() method to help convert this blob of text into three well-formed
paragraphs:

Downloaded from Ktunotes.in


$( ".container" )
.contents()
.filter(function() {
return this.nodeType === 3;
})
.wrap( "<p></p>" )
.end()
.filter( "br" )
.remove();
This code first retrieves the contents of <div class="container"> and then filters it for text nodes,
which are wrapped in paragraph tags. This is accomplished by testing the .nodeType property of
the element. This DOM property holds a numeric code indicating the node's type; text nodes use
the code 3. The contents are again filtered, this time for <br /> elements, and these elements are
removed.

Downloaded from Ktunotes.in

You might also like