From jQuery to DOM and ES6
Looking back in time, jQuery was created to cope with JavaScript implementation differences between browsers. But time have changed. For the better.
<div id="lead">lorem ipsum</div> <ul> <li class="green">First item</li> <li class="red">Second item</li> <li class="green">Third item</li> <li class="red">Last item</li> </ul> <p class="green status">A great status</p>
var lead = $('#lead'); var firstRedItem = $('.red').eq(0); var greenListItems = $('li.green'); // Adding `li` not to select the `p`.
const lead = document.getElementById('lead'); // ⚠️ no # const firstRedItem = document.querySelector('.red'); const greenListItems = document.querySelectorAll('li.green');
let name = "George"; name = name + " Abitbol"; // `name` is being re-assigned.console.log(name);
<div id="comments"> <p class="comment">This was great!</p> <p class="comment">I loved it :)</p> </div> <form> <textarea id="commentContent"></textarea> <button>Post comment</button> </form>
var commentContent = $('#commentContent').val(); // Skipping AJAX part $('#comments').append('<p class="comment">' + commentContent + '</p>');
const commentContent = document.getElementById('commentContent').value; const comments = document.getElementById('comments'); comments.insertAdjacentHTML('beforeend', `<p class="comment">${commentContent}</p>`);
$(selector).addClass('bold'); $(selector).removeClass('bold'); $(selector).toggleClass('bold');
// For one element selected with `getElementById` or `querySelector` element.classList.add('bold'); element.classList.remove('bold'); element.classList.toggle('bold'); // For multiple elements selected with `querySelectorAll`: elements.forEach((element) => { element.classList.add('bold'); // etc. });
<button id="useless-btn">Click me!</button>
$('#useless-btn').on('click', function(event) { alert('Thanks for clicking!'); });
const button = document.getElementById('useless-btn'); button.addEventListener('click', (event) => { alert('Thanks for clicking!'); });
// GET request $.ajax({ url: "https://swapi.co/api/people/", type: "GET" success: function(data) { console.log(data); } }); // POST request const data = { name: "a name", email: "an@email.com" }; $.ajax({ url: url, type: "POST", data: data, success: function(data) { console.log(data); } });
// GET request fetch("https://swapi.co/api/people/") .then(response => response.json()) .then((data) => { console.log(data); }); // POST requestconst data = { name: "a name", email: "an@email.com" }; fetch(url, { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify(data)}) .then(response => response.json()) .then((data) => { console.log(data); });