/    Sign up×
Community /Pin to ProfileBookmark

replacing jquery with plain javascript

I started to replace all of my jquery code with vanilla javascript, but ran into problems with event handling for dynamic html.

WIth Jquery, I can handle all events for a class as follows:
$(‘div’).on(‘mousedown’, ‘.atomdata’, function (e)
{
});

This would apply to all divs, regardless of when they are added. My application constantly updates html via a websocket, and these events work, I don’t need to do anything except replace the html.

I found that in plain vanilla javascript, when I add an event handler, it only applies to existing elements in the DOM, and does not automatically get applied to new elements that are added to the DOM later.

As far as I can see, JQuery is still indispensable and cannot be replaced by pure javascript. Is this correct?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumMay 03.2021 — This can be replaced by pure Javascript but it's no longer a oneliner:
``<i>
</i>document.addEventListener('click', event =&gt; {
if (event.target.classList.contains('atomdata')) {
// Element having class "atomdata" was clicked
}
});<i>
</i>
``

Shurely it would be easy to write a custum function doing the same.
Copy linkTweet thisAlerts:
@NogDogMay 03.2021 — > @startracer#1631119 JQuery is still indispensable and cannot be replaced by pure javascript. Is this correct?

Caveat, I am not a JavaScript expert. However...

JQuery is written in JavaScript, so by definition, anything it does could be done in "pure JavaScript". :) You can even see how it does things if so inclined: https://github.com/jquery/jquery
Copy linkTweet thisAlerts:
@startracerauthorMay 03.2021 — @Sempervivum#1631149 great, looks like that will do it thanks
Copy linkTweet thisAlerts:
@bwclovisMay 04.2021 — I'll take @NogDog#1631151 answer a bit further. We decided to cut the cord on jQuery about 2 years ago and we never looked back. This site helped tremendously:

[You might not need jQuery](http://youmightnotneedjquery.com/)
×

Success!

Help @startracer spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...