HomeLanguagesJavascriptD3.js html() Function

D3.js html() Function

The d3.html() function in d3.js is used to fetch and read the file of type HTML. It fetches the file as text first then parses the file as HTML.

Syntax:

d3.html(input[, init]);

Parameters: This function accepts two parameters as mentioned above and described below:

  • input: This parameter is the address of the input file.
  • init: This parameter takes a function.

Note: Please create a file named sample.html before going through the below given example.

Example 1: Filename: sample.html




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, 
        initial-scale=1.0">
</head>
  
<body>
    <p>I am a p tag</p>
    <script>
        alert("This is from d3.html() function")
    </script>
</body>
  
</html>


Filename: index.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>
    <script>
        d3.html("sample.html", function (d) {
            console.log(d);
        });
    </script>
</body>
  
</html>


Output:

Example 2: Filename: sample.html




<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width,
         initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>D3.js | d3.html() Function</h3>
    <p>I am a p tag</p>
</body>
</html>


Filename: index.html




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" path1tent=
        "width=device-width,initial-scale=1.0"/>
</head>
  
<body>
    <script src="https://d3js.org/d3.v4.min.js">
    </script>
    <script>
        d3.html("sample.html", function (d) {
            d = [].map.call(d.querySelectorAll("p"), (p) => {
                var h3 = d.querySelector("h3");
                document.write(`<h3>${h3.textContent}</h3>`);
                document.write(`<p>${p.textContent}</p>`);
            })
        });
    </script>
</body>
  
</html>


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32541 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6920 POSTS0 COMMENTS
Nicole Veronica
12036 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12143 POSTS0 COMMENTS
Shaida Kate Naidoo
7055 POSTS0 COMMENTS
Ted Musemwa
7292 POSTS0 COMMENTS
Thapelo Manthata
7014 POSTS0 COMMENTS
Umr Jansen
7000 POSTS0 COMMENTS