Mastering DOM Manipulation with D3.js: A Comprehensive Guide
Explore how to modify and update DOM elements using D3.js methods. Learn key techniques like using d3.select() for dynamic content manipulation
This section covers how to modify DOM elements using D3.js methods. After selecting elements with d3.select()
or d3.selectAll()
, you can use various methods to update or change their content and attributes.
Methods Overview
Method | Description |
---|---|
.text("content") |
Gets or sets the text content of the selected element. |
.append("element") |
Adds a new element inside the selected element, just before its end. |
.insert("element") |
Inserts a new element into the selected element before its end tag. |
.remove() |
Removes the selected element from the DOM. |
.html("content") |
Gets or sets the inner HTML of the selected element. |
.attr("name", "value") |
Gets or sets an attribute on the selected element. |
.property("name", "value") |
Gets or sets a property on the selected element. |
.style("name", "value") |
Gets or sets the style of the selected element. |
.classed("class", bool) |
Gets, adds, or removes a CSS class from the selection. |
Examples
Syntax
<div>
<p></p>
</div>
<p></p>
<script>
d3.select("p").text("This is a paragraph.");
</script>
Output
[Sets the text content of the first element to "This is a paragraph."]
Syntax
<p>First paragraph</p>
<p>Second paragraph</p>
<script>
d3.select("body").append("p").text("Third paragraph.");
</script>
Output
[Adds a new element with text "Third paragraph." at the end of
.]
Syntax
<div style="border:1px solid">
<p>First paragraph.</p>
</div>
<script>
d3.select("div").insert("p").text("Second paragraph.");
</script>
Output
[Inserts a new element with text "Second paragraph." inside
, before its end tag.]
Syntax
<p>First paragraph</p>
<p>Second paragraph</p>
<script>
d3.select("p").remove();
</script>
Output
[Removes the first element found.]
Syntax
<p>First paragraph</p>
<script>
d3.select("p").html("<span>This is new inner HTML.</span>");
</script>
Output
[Replaces the content of the element with new HTML.]
Syntax
<style>
.error {
color: red;
}
</style>
<body>
<p>Error: This is a dummy error.</p>
<script>
d3.select("p").attr("class", "error");
</script>
</body>
Output
[Adds the "error" class to the element.]
Syntax
<p>D3</p><input type="checkbox" />
<p>jQuery</p><input type="checkbox" />
<script>
d3.select("input").property("checked", true);
</script>
Output
[Checks the first checkbox.]
Syntax
<p>Error: This is a dummy error.</p>
<script>
d3.select("p").style("color", "red");
</script>
Output
[Sets the text color of the element to red.]
Syntax
<style>
.error {
color: red;
}
</style>
<body>
<p>This is an error.</p>
<script>
d3.select("p").classed('error', true);
</script>
</body>
Output
[Applies the "error" class to the element.]
These methods enable you to dynamically modify the DOM based on your data, creating powerful and interactive visualizations.