Menu

Post image 1
Post image 2
1 / 2
0

JavaScript DOM Manipulation: The Practical Guide

DEV Community·Alex Chen·17 days ago
#vG6SYQPU
Reading 0:00
15s threshold

JavaScript DOM Manipulation: The Practical Guide Stop reaching for jQuery. Vanilla JS can do everything. Selecting Elements // Single element const el = document . getElementById ( ' myId ' ); const firstBtn = document . querySelector ( ' .btn ' ); // CSS selector! // Multiple elements const allDivs = document . querySelectorAll ( ' div ' ); // NodeList (not array!) const allButtons = document . querySelectorAll ( ' button.primary ' ); // Convert to real array (for map/filter/reduce) const buttons = [... document . querySelectorAll ( ' button ' )]; // or: Array.from(document.querySelectorAll('button')) Enter fullscreen mode Exit fullscreen mode Creating Elements // Create from scratch const div = document . createElement ( ' div ' ); div . className = ' card ' ; div . id = ' card-1 ' ; div . innerHTML = ' <h2>Title</h2><p>Content</p> ' ; div . dataset . userId = ' 123 ' ; // data-user-id="123" // Add to page document . body . appendChild ( div ); parentElement .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More