Skip to research

Javascritp tricks

Momento della lettura
Circa 2 minuti
Étiquettes

Aide mémoire afin de ne plus utiliser jQuery.

Les Selections

/* 
  *  Selection par #id
  */
// IE 5.5+
document.getElementById('myElement');
// IE 8+
document.querySelector('#myElement');

/* 
  *  Selection par .class
  */
// IE 9+
document.getElementsByClassName('myElement');
// IE 8+
document.querySelectorAll('.myElement');

/* 
  *  Selection par Tagname
  */
// IE 5.5+
document.getElementsByTagName('div');
// IE 8+
document.querySelectorAll('div');

/* 
  *  Selection par Attributes
  */
// IE 8+
document.querySelectorAll('[data-foo-bar="someval"]');

/* 
  *  Selection par Pseudo-class
  */
// IE 10+
document.querySelectorAll('#myForm :invalid');

/* 
  *  Selection des children
  */
// IE 9+.
document.getElementById('myParent').children;

/* 
  *  Selection par Descendants
  */
document.querySelectorAll('#myParent A');

/* 
  *  Excluding Element
  */
// IE 9+
document.querySelectorAll('DIV:not(.ignore)');

/* 
  *  Multiple Selectors
  */
// IE 8+
document.querySelectorAll('DIV, A, SCRIPT');

 

Manipulation du DOM

/*  Creating Elements */
// IE 5.5+
document.createElement('div');


/*  Inserting Elements Before & After */
// IE 4+
document.getElementById('1')
    .insertAdjacentHTML('afterend', '<div id="1.1"></div>');
// IE 4+
document.getElementById('1')
    .insertAdjacentHTML('beforebegin', '<div id="0.9"></div>');


/*  Inserting Elements As Children */
// IE 4+
document.getElementById('parent')
    .insertAdjacentHTML('afterbegin', '<div id="newChild"></div>');
// IE 4+
document.getElementById('parent')
    .insertAdjacentHTML('beforeend', '<div id="newChild"></div>');


/*  Moving Elements */
// IE 5.5+
document.getElementById('parent')
    .appendChild(document.getElementById('orphan'));
// IE 5.5+
document.getElementById('parent')
    .insertBefore(document.getElementById('orphan'), document.getElementById('c1'));


/*  Removing Elements */
// IE 5.5+
document.getElementById('foobar').parentNode
    .removeChild(document.getElementById('foobar'));

/*  Adding CSS Classes */
// All modern browsers, with the exception of IE9
document.getElementById('foo').classList.add('bold');

// All browsers
document.getElementById('foo').className += 'bold';

/*  Removing CSS Classes */
// All modern browsers, with the exception of IE9
document.getElementById('foo').classList.remove('bold');

// All browsers
document.getElementById('foo').className = 
    document.getElementById('foo').className.replace(/^bold$/, '');


/*  Adding/Removing/Changing Attributes */
// IE 5.5+
document.getElementById('foo').setAttribute('role', 'button');
// IE 5.5+
document.getElementById('foo').removeAttribute('role');


/*  Adding & Changing Text Content */
// IE 5.5+
document.getElementById('foo').innerHTML = 'Goodbye!';

// IE 5.5+ but NOT Firefox
document.getElementById('foo').innerText = 'GoodBye!';

// IE 9+
document.getElementById('foo').textContent = 'Goodbye!';


/*  Adding/Updating Element Styles */
// IE 5.5+
document.getElementById('note').style.fontWeight = 'bold';

 

Ajax Requests

// GETting
var xhr = new XMLHttpRequest();
xhr.open('GET', 'myservice/username?id=some-unique-id');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('User\'s name is ' + xhr.responseText);
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();

// POSTing
var newName = 'John Smith',
    xhr = new XMLHttpRequest();

xhr.open('POST', 'myservice/username?id=some-unique-id');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
    if (xhr.status === 200 && xhr.responseText !== newName) {
        alert('Something went wrong.  Name is now ' + xhr.responseText);
    }
    else if (xhr.status !== 200) {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send(encodeURI('name=' + newName));

// URL Encoding
function param(object) {
    var encodedString = '';
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
            if (encodedString.length > 0) {
                encodedString += '&';
            }
            encodedString += encodeURI(prop + '=' + object[prop]);
        }
    }
    return encodedString;
}

// Sending and Receiving JSON
var xhr = new XMLHttpRequest();
xhr.open('PUT', 'myservice/user/1234');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        var userInfo = JSON.parse(xhr.responseText);
    }
};
xhr.send(JSON.stringify({
    name: 'John Smith',
    age: 34
}));

// Uploading Files
// encode
var formData = new FormData(),
    file = document.getElementById('test-input').files[0],
    xhr = new XMLHttpRequest();

formData.append('file', file);
xhr.open('POST', 'myserver/uploads');
xhr.send(formData);
// Send payload to request
var file = document.getElementById('test-input').files[0],
    xhr = new XMLHttpRequest();

xhr.open('POST', 'myserver/uploads');
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);

// CORS
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://someotherdomain.com');
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send('sometext');

// For cross-origin requests, some simple logic
// to determine if XDomainReqeust is needed.
if (new XMLHttpRequest().withCredentials === undefined) {
    var xdr = new XDomainRequest();
    xdr.open('POST', 'http://someotherdomain.com');
    xdr.send('sometext');
}

// JSONP
window.myJsonpCallback = function(data) {
    // handle requested data from server
};

var scriptEl = document.createElement('script');
scriptEl.setAttribute('src',
    'http://jsonp-aware-endpoint.com/user?callback=myJsonpCallback&id=123');
document.body.appendChild(scriptEl);