1

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 .contents() gets the children of each element in the set of matched elements including text and comment nodes, from the jQuery docs, but I don't think I understand what that description means. I've tried getting the children of .parent-class with:

let theChildren = document.querySelector('.parent-class').children;

but this doesn't do the same thing as .contents().find(".child-class") does.

EDIT: As requested in the comments I've made a new question as this one seems to not be specific enough.

Nikitas IO
  • 696
  • 5
  • 20
  • `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. – Rory McCrossan Apr 08 '20 at 09:08
  • @RoryMcCrossan I've tried omitting the content() method in my original code but that breaks the functionality. I'm trying to edit the styles of an embedded Twitter feed and I could only do that by getting the module's child nodes using the following snippet `$(".twitter-timeline").find(".timeline-Tweet-text").css("margin-bottom", "-10px");` – Nikitas IO Apr 08 '20 at 09:14
  • In that case you would be better served by asking a new question about the specific problem instead of a general question about the purpose of `contents()` – Rory McCrossan Apr 08 '20 at 09:14
  • I will edit the question then to better suit the specific problem. – Nikitas IO Apr 08 '20 at 09:15
  • You should start a new question, as you now have answers to this one – Rory McCrossan Apr 08 '20 at 09:16
  • I've posted the new question here: https://stackoverflow.com/questions/61099280/equivalent-of-jquerys-contents-find-chained-methods-in-pure-js – Nikitas IO Apr 08 '20 at 11:11

1 Answers1

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339