Converting jQuery selector to vanilla JavaScript: finding elements with class and tag combination

I’m working on converting some jQuery code to plain JavaScript and I’m stuck on one part. In jQuery I can easily select elements using something like $(".myClass div") to find all div elements inside elements with a specific class.

I need to know how to do the same thing using only vanilla JavaScript without jQuery. What’s the best way to select elements that match both a class name and a tag name pattern like this?

I’ve tried a few different approaches but can’t seem to get the same results. Any help would be great, thanks!

Yeah, document.querySelectorAll('.myClass div') is the direct replacement like others said, but you might want to try getElementsByClassName with getElementsByTagName for better performance sometimes. When I migrated from jQuery, I noticed the CSS selector approach got sluggish on bigger DOMs. If you’re doing frequent queries, cache the parent elements with document.getElementsByClassName('myClass') first, then loop through to find child divs - it’s usually faster. Just remember querySelectorAll returns a static NodeList, so if your DOM changes after the query, you’ll need to run it again. Not like the old jQuery versions that updated live.

yep, you can use document.querySelectorAll('.myClass div') to get all divs under elements with that class. if u need just the first one, document.querySelector('.myClass div') works too. should help ya out!

Yeah, querySelectorAll is the right way to go, but there are some performance things to keep in mind. I’ve converted a bunch of legacy jQuery apps, and querySelectorAll('.myClass div') works exactly like the jQuery version - just returns a NodeList instead of a jQuery object. You can’t chain jQuery methods on it. One gotcha: the NodeList is static, not like jQuery’s live collections. For iteration, just use forEach directly on the NodeList (modern browsers) or convert with Array.from() for older browsers. The syntax is identical to CSS selectors, so most jQuery patterns translate straight over.