How to convert this jquery code
$(element).find('.ui.dropdown')
to pure JS?
I need to convert a simple code in JQUERY to pure JS.
The element is a variable in my code, it comes from this code:
$.each($("[action]").toArray(), function(key, element)
fdomn-m
28.8k8 gold badges39 silver badges70 bronze badges
1 Answer 1
How about the following?
Array.prototype.slice.call(document.querySelectorAll('[action]')).forEach(function (element, index) {
element.querySelector('.ui.dropdown')
// do something to the element
});
As noted, Array.prototype.slice() is only needed if the browser you're running doesn't support NodeList.prototype.forEach(). For modern browsers you can actually do:
document.querySelectorAll('[action]').forEach(function (element, index) {
element.querySelector('.ui.dropdown')
// do something to the element
});
answered May 11, 2020 at 15:07
Hugo
3,9481 gold badge21 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
22 Comments
Hugo
yep, just for better browser support
Scott Marcus
Any browser that doesn't support
.forEach() on a node list also won't support Array.from. For best support use. Array.prototype.slice.call(document.querySelectorAll()).forEach(function(){});Sivakumar Tadisetti
I think OP wants to convert
$(element).find('.ui.dropdown') to Vanilla JSPatrick Roberts
@HereticMonkey in case you still haven't seen it, read the title of the first revision.
fdomn-m
@HereticMonkey personally I don't like the whole "you don't need to use jquery" - no, we don't need to but 20+ lines of code for 1 jquery line... think I'll keep using it thanks. So I comment that link and also normally move on - but was interested in the silly argument about which feature is "more compatible" with "older" versions of browsers (when neither is...). Then Sivakumar made the edit that removed all the formatting and I got too involved for my own good :)
|
lang-js
document.querySelectorAll("[action]").forEach(function(element){});elementhold? Can you console.log(element) and update the questionelementwill be a DOM node because they use.toArray(). It's terrible code, but that's what's been provided.array.mapcan be the best choice if you just want to find the elements and convert them to an array.