Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptD3.js selection.text() Function

D3.js selection.text() Function

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">neveropen</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;">neveropen</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:

RELATED ARTICLES

Most Popular

Recent Comments