DEV Community

Cover image for Day 4: Speedrunning jQuery in 1 hour
Kemystra
Kemystra

Posted on

Day 4: Speedrunning jQuery in 1 hour

The Feynman technique says that teaching a subject makes you better at it, which is what I'm trying to do here. You may correct me if you saw mistakes in this post

Editing HTML through jQuery

Up to this point, we have edited its properties, and its CSS styles. Now we're finally learning HTML manipulation with jQuery.

Firstly, text() and html() functions.

$("#textblock1").text("🍰 ipsum dolor sit amet ice cream.");
$("#smol-text").html("<em>A wild Pokemon appears.</em>");
Enter fullscreen mode Exit fullscreen mode

They add contents inside of the targeted element. The difference is that text() only allows plain text, while html() allows HTML tags to be rendered (kinda unsafe against XSS).

Secondly, remove(), appendTo(), and clone().

<div id="food">
    <p id="joe">Mama</p>
</div>

<p id="dessert">Crepe, mousse, parfait, etc.</p>
<p id="people">kids πŸ™Œ</p>

<script>
    $("#joe").remove(); // remove JOE MAMA
    $("#dessert").appendTo("#food"); // Move dessert into food
    $("#people").clone().appendTo("#food"); // Put kids as foods
</script>
Enter fullscreen mode Exit fullscreen mode

Note that clone() don't actually duplicate them, it's mostly used with appendTo() to actually work.

And thirdly, parent() and children().

$("p").parent().css("background-color", "black");
$("body").children().css("color", "pink");
Enter fullscreen mode Exit fullscreen mode

parent() refers to its direct parent, and children() refers to all of its children (Hint: children in plural).

What's amazing is how to refer to specific elements in a class or element type. Here we can use this (kinda unknown to me) CSS selector: element:nth-child(n), where element is a class or element type, and n is a number (which is one-indexed, so gonna remember that πŸ˜‰).

$("body:nth-child(3)").text("I'm number 3 lol");
Enter fullscreen mode Exit fullscreen mode

Or if you feel fancy, use :odd or :even:

$(".list:odd").css("background-color", "red");
$(".list:even").css("background-color", "blue");
Enter fullscreen mode Exit fullscreen mode

This count is zero-indexed, which must be remembered.

Afterwords

Yay, I got a lot done today πŸ₯³. A productive day indeed. We're gonna do SASS next, which is short, and I'm already using it. Gonna plow through it (and maybe even add a bit of React tomorrow! πŸ‘€)

Follow me on Github!
Also on Twitter!

Discussion (0)