This article mainly introduces 24 ES6 methods, these methods are quite practical, please remember this book, from time to time to read.

1. How do I hide all specified elements

const hide = (el) = > Array.from(el).forEach(e= > (e.style.display = 'none'));

// Example: Hide all '' elements on the page?
hide(document.querySelectorAll('img'))
Copy the code

2. How do I check if the element has the specified class?

Each node in the PAGE DOM has a classList object, which programmers can use to add, delete, and modify CSS classes on the node. With classList, programmers can also use it to determine whether a node is assigned a CSS class.

const hasClass = (el, className) = > el.classList.contains(className)

/ / case
hasClass(document.querySelector('p.special'), 'special') // true
Copy the code

3. How to switch an element’s class?

const toggleClass = (el, className) = > el.classList.toggle(className)

// remove p special class with class 'special'
toggleClass(document.querySelector('p.special'), 'special')
Copy the code

4. How do I obtain the scroll position of the current page?

const getScrollPosition = (el = window) = > ({
  x: el.pageXOffset ! = =undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset ! = =undefined ? el.pageYOffset : el.scrollTop
});

/ / case
getScrollPosition(); // {x: 0, y: 200}
Copy the code

5. How do I scroll smoothly to the top of the page

const scrollToTop = (a)= > {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8); }}/ / case
scrollToTop()
Copy the code

Tell the browser window. RequestAnimationFrame () — – you want to perform an animation, and required the browser until the next redraw calls the specified callback function to update this animation. This method takes as an argument a callback function that is executed before the browser’s next redraw.

RequestAnimationFrame: Advantage: It is up to the system to determine the timing of the callback function. If the refresh frequency is 60Hz, the callback function will be executed at each refresh interval without frame loss or stalling.

6. How do I check if the parent element contains child elements?

const elementContains = (parent, child) = >parent ! == child && parent.contains(child);/ / case
elementContains(document.querySelector('head'), document.querySelector('title')); 
// true
elementContains(document.querySelector('body'), document.querySelector('body')); 
// false
Copy the code

7. How do I check whether the specified element is visible in the viewport?

const elementIsVisibleInViewport = (el, partiallyVisible = false) = > {
  const { top, left, bottom, right } = el.getBoundingClientRect();
  const { innerHeight, innerWidth } = window;
  return partiallyVisible
    ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};

/ / case
elementIsVisibleInViewport(el); // Need left and right visibility
elementIsVisibleInViewport(el, true); // Full screen (top, bottom, left, right
Copy the code

8. How do I get all the images in an element?

const getImages = (el, includeDuplicates = false) = > {
  const images = [...el.getElementsByTagName('img')].map(img= > img.getAttribute('src'));
  return includeDuplicates ? images : [...new Set(images)];
};

// Example: includeDuplicates is true, indicating that duplicate elements need to be excluded
getImages(document.true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document.false); // ['image1.jpg', 'image2.png', '...']
Copy the code

9. How to determine whether the device is a mobile device or a desktop/laptop?

const detectDeviceType = (a)= >
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

/ / case
detectDeviceType(); // "Mobile" or "Desktop"
Copy the code

10.How to get the current URL?

const currentURL = (a)= > window.location.href

/ / case
currentURL() // 'https://google.com'
Copy the code

11. How to create an object that contains the current URL parameters?

const getURLParameters = url= >
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) = > ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

/ / case
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); / / {}
Copy the code

12. How do I turn a set of form elements into objects?

const formToObject = form= >
  Array.from(new FormData(form)).reduce(
    (acc, [key, value]) = > ({
      ...acc,
      [key]: value
    }),
    {}
  );

/ / case
formToObject(document.querySelector('#form')); 
// { email: '[email protected]', name: 'Test Name' }
Copy the code

13. How do I retrieve a set of properties indicated by a given selector from an object?

const get = (from. selectors) = >
  [...selectors].map(s= >
    s
      .replace(/\[([^\[\]]*)\]/g.'. $1.)
      .split('. ')
      .filter(t= >t ! = =' ')
      .reduce((prev, cur) = > prev && prev[cur], from));const obj = { selector: { to: { val: 'val to select'}},target: [1.2, { a: 'test'}};// Example
get(obj, 'selector.to.val'.'target[0]'.'target[2].a'); 
// ['val to select', 1, 'test']
Copy the code

14. How to call the provided function after waiting for the specified event?

const delay = (fn, wait, ... args) = >setTimeout(fn, wait, ... args); delay(function(text) {
    console.log(text);
  },
  1000.'later'
); 

// Print 'later' after 1 second
Copy the code

15. How do I trigger a specific event on a given element and optionally pass custom data?

const triggerEvent = (el, eventType, detail) = >
  el.dispatchEvent(new CustomEvent(eventType, { detail }));

/ / case
triggerEvent(document.getElementById('myId'), 'click');
triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' });
Copy the code

CustomEvent functions include Event, CustomEvent, and dispatchEvent

// Issue a resize built-in event to the window
window.dispatchEvent(new Event('resize'))
 

// Directly customize the Event using the Event constructor:
var event = new Event('build');
var elem = document.querySelector('#id')
// Listen on events
elem.addEventListener('build'.function (e) {... },false);
// Trigger the event.
elem.dispatchEvent(event);
Copy the code

CustomEvent can create a more highly CustomEvent, along with some data, as follows:

var myEvent = newCustomEvent(eventname, options); Where options can be: {detail: {... },bubbles: true.// Whether bubbles
  cancelable: false // Whether to cancel the default event
}
Copy the code

Detall can store some initialized information that can be called when triggered. Other attributes define whether the event has bubbling and so on.

While built-in events are triggered by the browser based on certain actions, custom events need to be triggered manually. The dispatchEvent function is used to trigger an event:

element.dispatchEvent(customEvent);
Copy the code

The above code shows that the customEvent event is triggered on element.

// add an appropriate event listener
obj.addEventListener("cat".function(e) { process(e.detail) });
 
// create and dispatch the event
var event = new CustomEvent("cat", {"detail": {"hazcheeseburger":true}}); obj.dispatchEvent(event); Using custom events requires compatibility issues, but jQuery is much simpler:// Bind custom events
$(element).on('myCustomEvent'.function(){});
 
// Trigger the event
$(element).trigger('myCustomEvent');
// In addition, you can also pass more parameter information when triggering custom events:
 
$( "p" ).on( "myCustomEvent".function( event, myName ) {$(this ).text( myName + ", hi there!" );
});
$( "button" ).click(function () {$("p" ).trigger( "myCustomEvent"["John"]); });Copy the code

16. How do I remove event listeners from elements?

const off = (el, evt, fn, opts = false) = > el.removeEventListener(evt, fn, opts);

const fn = (a)= > console.log('! ');
document.body.addEventListener('click', fn);
off(document.body, 'click', fn); 
Copy the code

17. How do I get the scale format for a given number of milliseconds?

const formatDuration = ms= > {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24.minute: Math.floor(ms / 60000) % 60.second: Math.floor(ms / 1000) % 60.millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val= > val[1]! = =0)
    .map(([key, val]) = > `${val} ${key}${val ! = =1 ? 's' : ' '}`)
    .join(', ');
};

/ / case
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); 
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
Copy the code

18. How do I get the difference (in days) between two dates?

const getDaysDiffBetweenDates = (dateInitial, dateFinal) = >
  (dateFinal - dateInitial) / (1000 * 3600 * 24);

/ / case
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); / / 9
Copy the code

19. How do I make GET requests to passed urls?

const httpGet = (url, callback, err = console.error) = > {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = (a)= > callback(request.responseText);
  request.onerror = (a)= > err(request);
  request.send();
};

httpGet(
  'https://jsonplaceholder.typicode.com/posts/1'.console.log
); 

// {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}
Copy the code

20. How do I make a POST request on a passed URL?

const httpPost = (url, data, callback, err = console.error) = > {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type'.'application/json; charset=utf-8');
  request.onload = (a)= > callback(request.responseText);
  request.onerror = (a)= > err(request);
  request.send(data);
};

const newPost = {
  userId: 1.id: 1337.title: 'Foo'.body: 'bar bar bar'
};
const data = JSON.stringify(newPost);
httpPost(
  'https://jsonplaceholder.typicode.com/posts',
  data,
  console.log
); 

// {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}
Copy the code

21. How do I create a counter with a specified range, step, and duration for a specified selector?

const counter = (selector, start, end, step = 1, duration = 2000) = > {
  let current = start,
    _step = (end - start) * step < 0 ? -step : step,
    timer = setInterval((a)= > {
      current += _step;
      document.querySelector(selector).innerHTML = current;
      if (current >= end) document.querySelector(selector).innerHTML = end;
      if (current >= end) clearInterval(timer);
    }, Math.abs(Math.floor(duration / (end - start))));
  return timer;
};

/ / case
counter('#my-id'.1.1000.5.2000); 
// Create a 2-second timer for the element with 'id= "my-id"
Copy the code

22. How do I copy strings to the clipboard?

  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly'.' ');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected); }};/ / case
copyToClipboard('Lorem ipsum'); 
// 'Lorem ipsum' copied to clipboard
Copy the code

23. How do I determine whether a page’s browser TAB is focused?

const isBrowserTabFocused = (a)= > !document.hidden;

/ / case
isBrowserTabFocused(); // true
Copy the code

24. How do I create a directory (if no directory exists)?

const fs = require('fs');
const createDirIfNotExists = dir= >(! fs.existsSync(dir) ? fs.mkdirSync(dir) :undefined);

/ / case
createDirIfNotExists('test'); 
Copy the code

The above methods are very practical, can solve a lot of development process problems, we make good use of it.