Open In App

D3.js selection.text() Function

Last Updated : 23 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The selection.text() function in d3.js is used to set the text content to the specified value of the selected elements thus, it replaces any existing child elements. If the value that is given is constant than all elements will be given that constant value.

Syntax:

selection.text([value]);

Parameters: This function takes only one parameter which is given above and described below:

  • value: Text content value to set.

Return Values: This function does not return any value.

Example 1:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width,initial-scale=1.0">
      
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <h1 style="color: green">GeeksforGeeks</h1>
    <div>
        <button>Click me</button>
    </div>
      
    <script>
        function func() {
              
            // Sets the text-content of the button
            var chk = d3.select("button")
                .text("This is the changed text");
            var text = document.querySelector("button");
        }
        let btn = document.querySelector("button");
        btn.addEventListener("click", func);
    </script>
</body>
  
</html>


Output:

  • Before clicking the button:

  • After clicking the button:

Example 2:

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" path1tent=
        "width=device-width, initial-scale=1.0">
      
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
</head>
  
<body>
    <h1 style="color: green;">GeeksforGeeks</h1>
    <div style="background-color: green; 
              width: fit-content; 
              padding: 10px; 
              margin-top: 5px;" class="btn">
        This text will be changed
    </div>
  
    <div style="background-color: green; 
              width: fit-content; 
              padding: 10px; 
              margin-top: 5px;" class="btn">
        This text will be changed
    </div><br>
    <br>
      
    <button class="Clickme">Change text</button>
      
    <script>
        function func() {
              
            // Selecting all buttons and
            // Setting the text content of the button
            var chk = d3.selectAll(".btn")
                .text("This text is changed");
            var text = document.querySelector("button");
        }
        let btn = document.querySelector(".Clickme");
        btn.addEventListener("click", func);
    </script>
</body>
  
</html>


Output: 

  • Before clicking the button:

  • After clicking the button:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads