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

