Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Creating and Appending Elements

Vanilla JavaScript in the browser now has many of the features of jQuery built-in.

Therefore, we don’t need to use jQuery to do many things.

In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.

Creating Elements

We can use jQuery’s $ function to create elements.

For instance, we can write:

$("<div/>");
$("<span/>");

to create a div and span respectively.

To do the same thing with vanilla JavaScript, we use the document.createElement method:

document.createElement("div");
document.createElement("span");

To add some content to the created elements, we can set the textContent property to add text.

Or we can attach child nodes with the appendChild method.

To add text content, we write:

const element = document.createElement("div");
element.textContent = "text"

And to add child node, we can write:

const element = document.createElement("div");
const text = document.createTextNode("text");
element.appendChild(text);

Updating the DOM

In jQuery, we can use the text method to update the text content of an element.

For instance, we can write:

$("div").text("New text");

And to return the text content of the selected element, we can write:

$("div").text();

to call text with no argument.

To set the text content of an element with vanilla JavaScript, we can write:

document.querySelector("div").textContent = "New text";

And to get the text content of the selected element, we write:

document.querySelector("div").textContent

In jQuery to append a new child element, we use the append method:

$(".search-result").append($("<div/>"));

We append a new div to the element with class search-result .

To do the same thing with vanilla JavaScript, we call appendChild :

const element = document.createElement("div");
document.querySelector(".search-result").appendChild(element);

We create the div with createElement and pass the returned element into appendChild .

Conclusion

We can create text nodes and elements and attach it easily into the DOM with vanilla JavaScript.

Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Events and Style Manipulation

Vanilla JavaScript in the browser now has many of the features of jQuery built-in.

Therefore, we don’t need to use jQuery to do many things.

In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.

Event Listening for Dynamically Added Elements

On many occasions, we want to listen to events on dynamically added elements.

In jQuery, we would use the on method to listen to the event on all the select elements.

For instance, we can write:

$("div").on("click", ".search-result", (e) => {
  //...
});

to listen to clicks on the elements with the search-result class in the div with the on method to attach the event listeners to them.

To do the same thing with vanilla JavaScript, we can use event delegation.

For instance, we can write:

document
  .querySelector('div')
  .addEventListener('click', (e) => {
    if (e.target.className === 'search-result') {
      //...
    }
  })

to call addEventListener on the div.

And then in the click event handler, we use e.target.className to get the class name of the element that we clicked on.

Then we compare that to see if we clicked on anything with the class search-result .

Triggering and Creating Events

In jQuery, we can use the trigger method to trigger an event.

For instance, we can write:

$(document).trigger("myEvent");
$("div").trigger("myEvent");

To do the same thing with vanilla JavaScript, we write:

document.dispatchEvent(new Event("myEvent"));
document.querySelector("div").dispatchEvent(new Event("myEvent"));

Wd call dispatchEvent on the selected element to trigger our one event.

Styling Elements

jQuery has the css method to let us style elements.

For instance, we can write:

$("div").css("color", "#000");

To do the same thing with vanilla JavaScript, we can write:

document.querySelector("div")
  .style.color = "#000";

We set the style.color property to set the CSS color property of the selected div.

We can also pass in an object into jQuery’s css method:

$("div").css({
  "color": "#000",
  "background-color": "red"
});

To do the same thing with vanilla JavaScript, we just set the properties of the style object property to the values we want:

const div = document.querySelector("div");
div.style.color = "#000";
div.style.backgroundColor = "red";

We can also set the style.cssText property to set multiple styles:

const div = document.querySelector("div");
div.style.cssText = "color: #000; background-color: red";

hide() and show()

jQuery comes with the hide method to let us hide the selected elements.

And we can use jQuery’s show method to show the selected elements.

For instance, we can write:

$("div").hide();
$("div").show();

to hide and show the div respectively.

To do the same thing with vanilla JavaScript, we can set the display CSS property to the value we want with JavaScript:

document.querySelector("div").style.display = "none";
document.querySelector("div").style.display = "block";

We hide the div by setting style.display to 'none' .

And we show the div by setting style.display to 'block' .

Conclusion

We can add event listeners and manipulate styles easily with vanilla browser JavaScript.

Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Wait for Document Load, Classes, and HTTP Requests

Vanilla JavaScript in the browser now has many of the features of jQuery built-in.

Therefore, we don’t need to use jQuery to do many things.

In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.

Wait for Document to be Ready

With jQuery, we can use the $(document).ready callback to run code when the DOM is loaded:

$(document).ready(() => {  
  //...  
});

To do the same thing with vanilla JavaScript, we can listen to the DOMContentLoaded event on the document :

document.addEventListener("DOMContentLoaded", () => {  
  //...  
});

Working with Classes

jQuery has methods to let us add, remove or toggle classes of an element:

$("div").addClass("focus");  
$("div").removeClass("focus");  
$("div").toggleClass("focus");

addClass lets us add the focus class to the div.

removeClass lets us remove the focus class to the div.

toggleClass lets us toggle the focus class to the div.

To do the same thing with vanilla JavaScript, we can use the methods in the classList property of an element.

For instance, we can write:

const div = document.querySelector("div");  
div.classList.add("focus");  
div.classList.remove("focus");  
div.classList.toggle("focus");

classList.add adds the focus class.

classList.remove removes the focus class.

And classList.toggle toggles the focus class.

We can also add or remove multiple classes with:

const div = document.querySelector("div");  
div.classList.add("focus", "highlighted");  
div.classList.remove("focus", "highlighted");

classList.add adds the focus and highlighted classes.

classList.remove removes the focus and highlighted classes.

We can also use the classList.replace method to replace one class with another.

For instance, we can write:

document.querySelector("div").classList.replace("focus", "blurred");

The focus class is replaced with the blurred class with classList.replace .

Checking if an Element has a Class

jQuery comes with the hasClass method to check if an element has the given class.

For instance, we can write:

if ($("div").hasClass("focus")) {  
  //...  
}

To do the same thing with vanilla JavaScript, we can use the classList.contains method:

if (document.querySelector("div").classList.contains("focus")) {  
  //...  
}

Network Requests

jQuery comes with the get method to make GET requests.

It also comes with the ajax method to let us make any requests.

For instance, we can use ajax by writing:

$.ajax({  
  url: "https://yesno.wtf/api"  
}).done((data) => {  
  console.log(data)  
}).fail(() => {  
  // Handle error  
});

And we can use get by writing:

$.get({  
  url: "https://yesno.wtf/api"  
}).done((data) => {  
  console.log(data)  
}).fail(() => {  
  // Handle error  
});

With vanilla JavaScript, we can just use the fetch method:

(async () => {  
  try {  
    const res = await fetch('https://yesno.wtf/api')  
    const data = await res.json()  
    console.log(data)  
  } catch (error) {  
    console.log(error)  
  }  
})()

We call res.json to turn the JSON response data object into a JavaScript object.

fetch returns a promise which is more convenient than using done and fail callbacks.

Conclusion

We can use vanilla JavaScript to wait for the DOM to be ready, make HTTP requests, and manipulate element classes easily.

Categories
JavaScript jQuery

jQuery to Vanilla JavaScript Transition Cheat Sheet — Basic Operations 

Vanilla JavaScript in the browser now has many of the features of jQuery built in,

Therefore, we don’t need to use jQuery to do many things.

In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.

Selecting Elements

We can use the querySelector method to select a single element with the given selector in vanilla JavaScript.

Vanilla JavaScript also has the querySelectorAll method to select multiple elements with the given selector with vanilla JavaScript.

For instance, we can write:

document.querySelector("div");

to select the first div in the document.

And select all the divs with:

document.querySelectorAll("div");

querySelectorAll returns a NodeList object, which is an iterable object with all the selected nodes inside.

In jQuery, we have:

$("div");

to select all the divs.

Run a Function on All Selected Elements

In jQuery, we can run a function on all selected elements.

For instance, we can hide all the divs by writing:

$("div").hide();

To do the same thing with vanilla JavaScript, we can use the forEach method:

document.querySelectorAll("div")
  .forEach(div => {
    div.style.display = "none"
  })

We can also use the for-of loop:

for (const div of document.querySelectorAll("div")) {
  div.style.display = "none"
}

The NodeList returned by querySelector can also be spread:

const divs = [...document.querySelectorAll("div")]
divs
  .forEach(div => {
    div.style.display = "none"
  })

divs is now an array instead of a NodeList.

This means we can run many array methods on it.

Finding an Element within Another

To find an element within another with jQuery, we use the find method:

const div = $("div");
//...
div.find(".box");

To do the same thing with vanilla JavaScript, we can use querySelector to find one element and querySelectorAll to find all instances of the element with the given selector.

So we write:

const div = document.querySelector('div')
//...
div.querySelector(".box");

to find the first element with class box in the div.

And we write:

const div = document.querySelector('div')
//...
div.querySelectorAll(".box");

to find all elements with class box in the div.

Traversing the Tree with parent(), next(), and prev()

jQuery has the parent method to get the parent element of an element.

jQuery’s next method returns the next sibling element of an element.

And jQuery’s prev method returns the previous sibling element of an element.

To use them, we can write:

$("div").next();
$("div").prev();
$("div").parent();

In vanilla JavaScript, we can write:

const div = document.querySelector("div");
div.nextElementSibling;
div.previousElementSibling;
div.parentElement;

nextElementSibling returns the next sibling element.

previousElementSibling returns the previous sibling element.

And parentElement returns the parent element.

Working with Events

jQuery lets us add event handlers easily to an element.

For instance, we can write:

$("button").click((e) => {
  /* handle click event */
});
$("button").mouseenter((e) => {
  /* handle click event */
});
$(document).keyup((e) => {
  /* handle key up event */
});

to add a click event handler, mouseenter event handler, and keyup event handler on the element that’s selected respectively.

To do the same thing with vanilla JavaScript, we can use the addEventListener method:

document
  .querySelector("button")
  .addEventListener("click", (e) => {
    /* ... */
  });

document
  .querySelector("button")
  .addEventListener("mouseenter", (e) => {
    /* ... */
  });

document
  .addEventListener("keyup", (e) => {
    /* ... */
  });

We just select the element with querySelector and call addEventListener with the event name as the first argument and the event handler callback as the 2nd argument.

Conclusion

We can do many basic DOM operations like selecting elements, traversing the DOM tree, and adding event listeners to elements with vanilla JavaScript.

Categories
jQuery

jQuery — Key Events and Select Element by Type

jQuery is a popular JavaScript for creating dynamic web pages.

In this article, we’ll look at how to using jQuery in our web apps.

.keypress()

We can use the keypress method to listen to keypress events or trigger it.

For example, if we have:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there">
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the keypress event on the input by writing:

$("#target").keypress(function() {
  console.log("Handler for .keypress() called.");
});

We can also trigger the keypress event when we click on the div with ID other by writing:

$("#target").keypress(function() {
  console.log("Handler for .keypress() called.");
});$("#other").click(function() {
  $("#target").keypress();
});

.keyup()

The .keyup() method lets us listen to the keyup event or trigger it.

For instance, if we have:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there">
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

Then we can listen to the keyup event on the input by writing:

$("#target").keyup(function() {
  console.log("Handler for .keypress() called.");
});

We can also trigger the keyup event when we click on the div with ID other by writing:

$("#target").keyup(function() {
  console.log("Handler for .keypress() called.");
});$("#other").click(function() {
  $("#target").keyup();
});

:lang() Selector

The :lang selector lets us select all elements of the specified language.

For example, if we have the following HTML:

<div lang="en-us">red
  <div>white
    <div>and blue</div>
  </div>
</div>
<div lang="es-es">rojo
  <div>amarillo
    <div>y rojo</div>
  </div>
</div>

And CSS:

.spain {
  background-color: red;
  color: #ff0;
}.usa {
  background-color: red;
  color: #fff;
}

Then we can add the different classes to the div with different lang attribute values by writing:

$("div:lang(en-us)").addClass("usa");
$("div:lang(es-es)").addClass("spain");

.last()

We can get the last element in a set of matched elements with the .last method.

For example, if we have:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
</ul>

Then we add a red background to the last li by writing:

$("li").last().css("background-color", "red");

We get the li's and then call last to get the last one.

:last-child Selector

The :last-child selector selects all elements that are the last child of the parent.

For example, if we have the following HTML:

<div>
  <span>John,</span>
  <span>Karl,</span>
  <span>Brandon,</span>
  <span>Sam</span>
</div>
<div>
  <span>James,</span>
  <span>Mary,</span>
  <span>Ralph,</span>
  <span>David</span>
</div>

and CSS:

span.solast {
  text-decoration: line-through;
}

Then we can make the last span of each div red and add a strikethrough when web hover over them by writing:

$("div span:last-child")
  .css({
    color: "red",
    fontSize: "80%"
  })
  .hover(function() {
    $(this).addClass("solast");
  }, function() {
    $(this).removeClass("solast");
  });

:last-of-type Selector

We can get the last element of a given type with the :last-pf-type selector.

For example, if we have the following HTML:

<div>
  <span>Corey,</span>
  <span>Yehuda,</span>
  <span>Adam,</span>
  <span>Todd</span>
</div>
<div>
  <span>James,</span>
  <span>Mary,</span>
  <span>Tim,</span>
  <b>Nobody</b>
</div>

and CSS:

span.solast {
  text-decoration: line-through;
}

Then we can make the last span of each div red and add a strikethrough when web hover over them by writing:

$("span:last-of-type")
  .css({
    color: "red",
    fontSize: "80%"
  })
  .hover(function() {
    $(this).addClass("solast");
  }, function() {
    $(this).removeClass("solast");
  });

Conclusion

We can listen to key events and get elements by type with jQuery.