genbodev2
4/3/2017 - 8:46 AM

JS snippets

JS snippets

// Shuffling array’s elements

var list = [1, 2, 3];  
console.log(list.sort(function() {  
    return Math.random() - 0.5
})); // [2,1,3]
// Short-circuits conditionals

if (conected) {  
    login();
}

// short
conected && login();
// id
var elem = document.getElementById('content');

// tag
var elements = document.getElementsByTagName('div');

// all tags
var children= elem.getElementsByTagName('*');

// attr name
var elems = document.getElementsByName('age');

// classname
var articles = document.getElementsByClassName('article');

// css selector
var elements = document.querySelectorAll('ul > li:last-child');

// first css selector
var elem = document.querySelector('#id');

// match
if (elems[i].matches('a[href$="zip"]')) {
  console.log(elems[i].href);
}

// parent css selector
alert(numberSpan.closest('li').className); // need poly

// Detecting properties in an object
if ('querySelector' in document) {  
    document.querySelector("#id");
} else {
    document.getElementById("id");
}
// Replace all

var string = "john john";  
console.log(string.replace(/hn/, "ana")); // "joana john"  
console.log(string.replace(/hn/g, "ana")); // "joana joana"
// Merging arrays

var array1 = [1, 2, 3];  
var array2 = [4, 5, 6];  

console.log(array1.concat(array2)); // [1,2,3,4,5,6];

// fast
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
// Default values using || operator

function User(name, age) {  
    this.name = name || "Oliver Queen";
    this.age = age || 27;
}
// Converting to number using + operator

function toNumber(strNumber) {  
    return +strNumber;
}
console.log(toNumber("1234")); // 1234  
console.log(toNumber("ACB")); // NaN
// Converting NodeList to Arrays

var elements = document.querySelectorAll("p"); // NodeList  
var arrayElements = [].slice.call(elements); // Now the NodeList is an array  
var arrayElements = Array.from(elements); // This is another way of converting NodeList to Array
// Caching the array.length in the loop for BIG ARRAY

for (var i = 0, length = array.length; i < length; i++) {  
    console.log(array[i]);
}
// Array truncation

var array = [1, 2, 3, 4, 5, 6]; 
array.length = 3;  
console.log(array.length); // 3  
console.log(array); // [1,2,3]