How to create a line break in an HTML element using D3.js

Viewed 1633

I can't seem to format my tooltip into 4 separate lines. I have a p element and want to break it up. I have tried adding br and \n and they don't seem to help.

var tooltip = d3.select("body")
    .append("div")
    .attr('class', 'tooltip');

tooltip.append("p");

//Here I go through my data using selectAll and append circles. the '.on' attribute is when I hover over a circle I want to see the tooltip

.on("mousemove", function(d){

if (d.source == "target") {              
    tooltip.select("p").text(d.source);
} else {                       
    tooltip.select("p").text("Line 1: " + "this is line 1" + "\n" + "line 2: " + "this is line 2");
}
2 Answers

Instead of using .text(), use .html(), that way you can use <br> like so:

tooltip.select("p").html("Line1: this is line 1 <br> line 2: this is line 2");

If that doesn't work, try

tooltip.select("p").html(function(){
    return "Line 1: this is line 1 <br> line 2: this is line 2"
});

As this is how I currently use .html()

Just as a complement to the other answer:

You can use either html() or text() methods here. The difference between them is that text() uses textContent, while html() uses innerHTML.

We can see this at the source code for text():

this.textContent = value;

And this at the source code for html():

this.innerHTML = value;

Therefore, each method has its particularities.

Using html()

As already explained, you can use html() with <br>:

d3.select("p").html("Line 1: " + "this is line 1" + "<br>" + "line 2: " + "this is line 2");
<p></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Using text()

For using the text() method, just as in your code, you have to select an adequate value for white-space, like pre:

var p = d3.select("p");
p.text("Line 1: " + "this is line 1" + "\n" + "line 2: " + "this is line 2");
p {
  white-space: pre;
}
<p></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Related