var content = document.getElementById('whatever').textContent;
var $content = $('#whatever').text();
document.getElementById('whatever').textContent = "Hello World";
$('#whatever').text('Hello World');
document.getElementById('whatever').innerHTML = "<ul class=\"messages\">"
+ "<li>Hello World</li>"
+ "</ul>";
$('#whatever')
.html('<ul class="messages"><li>Hello World</li></ul>');
var content = document.getElementById('whatever').innerHTML;
var elementAndContent = document.getElementById('whatever').outerHTML;
var $content = $('#whatever').html();
var $elementAndContent = $('#whatever').prop('outerHTML'); // Beware SVGs
// 1
document.getElementById('something').innerHTML = '<p>Hello</p>';
// 2
var newContent = document.createElement('a');
newContent.textContent = "Go to documents";
newContent.createAttribute('href', '....');
// 3
var $newPara = $('<p>Hi ' + name + '</p>');
var el = document.getElementById('whatever');
var parent = el.parentNode;
var newContent = document.createElement('p');
newContent.textContent = "After";
var newPreContent = document.createElement('p');
newPreContent.textContent = "Before";
el.appendChild(newContent);
var firstLi = document.querySelectorAll('ul li')[0];
list.insertBefore(newPreContent, firstLi);
$('#whatever').append('<p>After</p>');
$('#whatever').prepend(newPreContent);
var element = document.getElementById('ul'); // assuming ul exists
var fragment = document.createDocumentFragment();
var browsers = ['Firefox', 'Chrome', 'Opera',
'Safari', 'Internet Explorer'];
browsers.forEach(function(browser) {
var li = document.createElement('li');
li.textContent = browser;
fragment.appendChild(li);
});
element.appendChild(fragment);
var element = document.getElementById('ul'); // assuming ul exists
var fragment = document.createDocumentFragment();
var browsers = ['Firefox', 'Chrome', 'Opera',
'Safari', 'Internet Explorer'];
browsers.forEach(function(browser) {
var li = document.createElement('li');
li.textContent = browser;
fragment.appendChild(li);
});
element.appendChild(fragment);
var para = document.createElement('p');
para.textContent = "Hello";
document.body.innerHTML = para;
When you try to pass an object to a property that expects a string, it calls that object's toString method and inserts the output
var el = document.getElementById('whatever');
// There is also 'afterstart' and 'beforeend' to append and prepend
el.insertAdjacentHTML('beforestart', '<p>Before</p>');
el.insertAdjacentHTML('afterend', '<p>After</p>');
$('#whatever').before('<p>Before</p>');
$('#whatever').after('<p>After</p>');
Wrapping a node:
// Wrap an element
$("#target").wrap("<div class='new'></div>");
// Wrap a series of elements
$("li .inner").wrapAll("<div class='new' />");
// Wrap the contents of a selection of elements
$("#target").wrapInner("<div class='new'></div>");
Wrap can also take a function to construct layers of wrapping html
var el = document.getElementById('whatever');
var parent = el.parentNode;
parent.removeChild(el); // returns the removed node
var $el = $('#whatever');
var $parent = $el.parent();
var n = $parent.remove($el); // doesn't keep jQuery data on these nodes
var $m = $parent.detach($el); // does, so you can re-insert the node
Cloning a node:
var el = document.getElementById('whatever');
var clone = el.cloneNode(true); // true for deep cloning
document.getElementById('receiver').appendChild(clone);
var $clone = $('#whatever').clone();
$('#receiver').append($clone);
Removing a node:
// <input type="text" id="myTextBox">
var myInput = document.getElementById('myTextBox');
var value = myInput.value;
myInput.value = '10';
var $myInput = $('#myTextBox');
var $value = $myInput.val();
$myInput.val('10');
When using forms:
// <input type="text" placeholder="Enter name" name="name" id="name">
var button = document.getElementById('toggler');
var $jqButton = $('#jq-toggler');
var input = document.getElementById('name');
var $input = $(input);
button.addEventListener('click', function(e) {
var isDisabled = input.getAttribute('disabled');
alert(!!isDisabled);
if (!!isDisabled) {
input.removeAttribute('disabled');
} else {
input.setAttribute('disabled', 'disabled');
}
});
$jqButton.on('click', function($e) {
var isDisabled = $input.prop('disabled');
alert(!!isDisabled);
if (!!isDisabled) {
$input.prop('disabled', false);
} else {
$input.prop('disabled', true);
}
});
Beware attr() vs prop() in jQuery
// <button id="buy" data-price="1.24">Buy</button>
var $buyButton = $('#buy');
var buyBtn = document.getElementById('buy');
// GETTER
var price =$buyButton.data('price');
var price = buyBtn.dataset.price
console.log(price); // "1.24"
// SETTER
$buyButton.data('price', '6.50');
buyBtn.dataset.price = '6.50';
console.log($buyButton.data('price')); // "6.50"
Order of occurance:
<ul class="carsList"> <!-- Here when JS was bound -->
<li>Ferarri <button class="delete">×</button></li> <!-- Templated in later -->
<li>Bugatti <button class="delete">×</button></li><!-- Templated in later -->
</ul>
// Get the parent DIV, add click listener...
document.querySelectorAll(".carsList")[0].addEventListener("click", function(e) {
// e.target was the clicked element (unless <i>, then check parent too!
if (e.target && e.target.matches("button.delete")) {
// Delete button was clicked, so do something...
}
});
// Get the parent UL, add click listener...
$(".carsList").on("click", '.delete', function(e) {
// binds on page load to existing <ul>
// Second parameter selects the internal element (i.e. the delete buttons in the <li>s
// 'this' will be bound to the target button
});
jQuery
Bad:
var person = { name: 'James', age: 39, height: 1.75 };
// Normal JS
var profileFrag = document.createElement('DIV');
profileFrag.className = "profile";
profileFrag.innerHTML = "<dl><dt>Name:</dt><dd>" + person.name +
"</dd><dt>Age:</dt><dd>" + person.age + "</dd><dt>Height:</dt><dd>" +
person.height + "</dd></dl>";
document.getElementById("target").innerHTML = profileFrag;
// jQuery
$('#target').html('<div class="profile"><dl><dt>Name:</dt><dd>' +
person.name + '</dd><dt>Age:</dt><dd>' + person.age + '</dd><dt>Height:</dt><dd>' +
person.height + '</dd></dl></div>');
Good:
<div class="entry">
<h3>{{title}}</h3>
<div class="body">
<p>{{detailText}}</p>
</div>
</div>
It is cleaner if I can use the above, providing context
(i.e. the values that go in the 'holes')
AJAX
<!-- Typical (simple) XML -->
<person>
<name>James</name>
<age>38</age>
</person>
Look familiar?? That's because HTML is a subset of XML. i.e. It's XML that we've agreed as a way to represent web page elements.
var tutors = [
{name: 'frank', age: 23, isQualified: false},
{name: 'tom', age: 37, isQualified: true}
];
var tutorData = JSON.stringify(tutors);
console.log(tutorData);
// [{"name": "frank", "age": 23, "isQualified": false}, ...etc.];
Javascript to JSON
var person = {name: 'fred'};
var personJSON = JSON.stringify(person);
// personJSON: "{"name": "fred"}"
var personJSON = '{"name": "fred"}';
var person = JSON.parse(personJSON);
// person: {name: 'fred'}
JSON to JavaScript
Value | State | Description |
0 | UNSENT | Client has been created. open() not called yet. |
1 | OPENED | open() has been called. |
2 | HEADERS_RECEIVED | send() has been called, and headers and status are available. |
3 | LOADING | Downloading; responseText holds partial data. |
4 | DONE | The operation is complete. |
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log('state changed', xmlhttp.readyState);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
console.log('response: ', xmlhttp.responseText);
console.log('parsed: ', JSON.parse(xmlhttp.responseText));
}
else if (xmlhttp.status === 404) {
alert('The resource was not found');
}
else {
alert('Error: Call to server failed with code: ' + xmlhttp.status);
}
}
};
xmlhttp.open("GET", "https://jsonplaceholder.typicode.com/users/1", true);
xmlhttp.send();
Note that you have to parse the response before using it JSON.parse(response);
$.ajax({
method: 'GET', //optional. GET (default), POST, PUT, DELETE, etc.
context: document.body, //optional. Scopes the response to a part of your page
data: {}, // <-- body of the request goes here
url: '//api.github.com/users/jmsherry'
}).done(function(response){
console.log(response);
}).fail(function(error){ //just to show you how to error catch
console.error(error);
}).always(function(){ //this happens after EVERY ajax call
console.info("ajax call made");
});
jQuery takes care of all of that, including parsing the JSON response.
fetch('http://example.com/cats.json', {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // *manual, follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(function(response) {
return response.json();
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.error(error);
});
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Can be used client and server side
Let's combine these two technologies (templating and AJAX):
Maybe you can try it with your github account: call https://api.github.com/users/jmsherry