DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • ReactJS for AI and Machine Learning: A Powerful Combination
  • jQuery vs. Angular: Common Differences You Must Know
  • Resolver in Angular: An Overview
  • From Low Code to No Code: Borne to the Extreme Necessity to Solve Key Tech

Trending

  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  • Top Book Picks for Site Reliability Engineers
  • Automatic Code Transformation With OpenRewrite
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  1. DZone
  2. Coding
  3. Frameworks
  4. JavaScript Without jQuery: Tips and Practical Examples

JavaScript Without jQuery: Tips and Practical Examples

All the cool kids use jQuery, but for a lot of it's functionality it's almost as easy to do it yourself. Look at these simple examples.

By 
Jean-Baptiste Jung user avatar
Jean-Baptiste Jung
·
Jun. 28, 16 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
18.7K Views

Join the DZone community and get the full member experience.

Join For Free

jQuery is extremely popular amongst front-end developers and is the preferred JavaScript framework of most coders. But even if jQuery can simplify your JS development and add a lot of possibilities, there’s cases where you can’t use jQuery. Here are some tips and practical examples about how to do things you usually do with jQuery without using the popular framework.

Listening for Document Ready

A page can’t be manipulated safely until the document is “ready”. For that reason, we developers have taken the habit to wrap all of our JS code inside the jQuery $(document).ready() function:

$( document ).ready(function() {
    console.log( "ready!" );
});

The same result can be achieved easily using pure JavaScript:

document.addEventListener('DOMContentLoaded', function () {
    console.log( "ready!" );
});

Adding Event Listeners

Event Listeners are a very important part of JavaScript development. jQuery has a very easy way to handle them:

$(someElement).on('click', function() {
    // TODO event handler logic
});

You don’t need jQuery to create event listeners in JavaScript. Here’s how to do so:

someElement.addEventListener('click', function() {
    // TODO event handler logic
});

Selecting Elements

jQuery makes it super easy to select elements using an ID, a class name, tag name, etc:

// By ID
$('#myElement');

// By Class name
$('.myElement');

// By tag name
$('div');

// Children
$('#myParent').children();

// Complex selecting
$('article#first p.summary');

Pure JavaScript features various way to select elements. All of the methods below work on all modern browsers as well as IE8+.

// By ID
document.querySelector('#myElement');

// By Class name
document.querySelectorAll('.myElement');

// By tag name
document.querySelectorAll('div');

// Children
$('#myParent').children();

// Complex selecting
document.querySelectorAll('article#first p.summary');

Using AJAX

As most of you know, AJAX is a set of technologies allowing you to create asynchronous web applications. jQuery has a set of useful methods for AJAX, including get() as shown below:

$.get( "ajax/test.html", function( data ) {
    $( ".result" ).html( data );
    alert( "Load was performed." );
});

Although jQuery makes AJAX development easier and faster, it’s a sure thing that you don’t need the framework to use AJAX:

var request = new XMLHttpRequest();
request.open('GET', 'ajax/test.html', true);

request.onload = function (e) {
    if (request.readyState === 4) {

        // Check if the get was successful.

        if (request.status === 200) {
            console.log(request.responseText);
        } else {
            console.error(request.statusText);
        }
    }
};

Adding and Removing Classes

If you need to add or remove an element’s class, jQuery has two dedicated methods to do so:

// Adding a class
$('#foo').addClass('bold');

// Removing a class
$('#foo').removeClass('bold');

Without jQuery, adding a class to an element is pretty easy. To remove a class, you’ll need to use the replace() method:

// Adding a class
document.getElementById('foo').className += 'bold';

// Removing a class
document.getElementById('foo').className = document.getElementById('foo').className.replace(/^bold$/, '');

Fade In

Here’s a practical example of why jQuery is so popular. Fading an element only takes a single line of code:

$(el).fadeIn();

The exact same effect can be achieved in pure JavaScript, but the code is way longer and more complicated.

function fadeIn(el) {
  el.style.opacity = 0;

  var last = +new Date();
  var tick = function() {
    el.style.opacity = +el.style.opacity + (new Date() - last) / 400;
    last = +new Date();

    if (+el.style.opacity < 1) {
      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
    }
  };

  tick();
}

fadeIn(el);

Source: Stack Overflow

Hiding and Showing Elements

Hiding and showing elements is a very common task. jQuery offers the hide() and show() methods for modifying the display of an element.

// Hiding element
$(el).hide();

// Showing element
$(el).show();

In pure JavaScript, showing or hiding elements isn’t more complicated:

// Hiding element
el.style.display = 'none';

// Showing element
el.style.display = 'block';

DOM Manipulation

Manipulating the DOM with jQuery is very easy. Let’s say you would like to append a <p> element to #container:

$("#container").append("<p>more content</p>");

Doing so in pure JavaScript isn’t much of a big deal either:

document.getElementById("container").innerHTML += "<p>more content</p>";

Further Reading

To complete this article, I’ve compiled five very useful blog posts and websites dedicated to using JavaScript without jQuery. All links below feature many practical examples.

  • jQuery VS raw JavaScript
  • A year without jQuery
  • You might not need jQuery
  • 10 tips for writing JavaScript without jQuery
  • You don’t need jQuery (anymore)
JQuery JavaScript framework

Published at DZone with permission of Jean-Baptiste Jung, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • ReactJS for AI and Machine Learning: A Powerful Combination
  • jQuery vs. Angular: Common Differences You Must Know
  • Resolver in Angular: An Overview
  • From Low Code to No Code: Borne to the Extreme Necessity to Solve Key Tech

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!