Jquery's Contents() Methods In Pure Js
So I've been trying to do the following bit of code without importing the jQuery library: $('.parent-class').contents().find('.child-class').css('color', 'red'); I know that .cont
Solution 1:
contents()
is primarily used in jQuery when you need to select text nodes. In the first code sample you have it's not needed at all, as you use find()
to select elements with a class. These lines of jQuery would serve the same purpose:
$(".parent-class").find(".child-class").css("color", "red");
$(".parent-class .child-class").css("color", "red");
In plain JS this would be:
document.querySelectorAll('.parent-class .child-class').forEach(el => el.style.color = 'red');
Note querySelectorAll()
there. This will return a nodeList which you need to iterate through to update the style in the same way the jQuery code does.
There is no explicit JS equivalent of contents()
because you traverse manually to find the nodes you want to target, or use querySelector()
, getElementByX()
etc to target the elements.
Solution 2:
This gets the first child-class in the first parent-class:
let theChildren = document.querySelector('.parent-class .child-class');
This gets all child-class in every parent-class:
let theChildren = document.querySelectorAll('.parent-class .child-class');
Post a Comment for "Jquery's Contents() Methods In Pure Js"