By Alvin Alexander. Last updated: January 23, 2024
As a note to self, while working on my “Generate the Table Of Contents code for this website,” I just needed to do create some “nested DIV” content using Jsoup, Scala 3, and Scala-CLI, and with the help of ChatGPT, I came up with this working code:
//> using scala "3"
//> using lib "org.jsoup:jsoup:1.17.2"
import org.jsoup.Jsoup
import org.jsoup.nodes.{Document, Element}
/*
The output looks like this:
<html>
<head></head>
<body>
<div id="container">
<p>This is existing content</p>
<div class="nested-div">
Nested Div 1 content
<div class="nested-div">
Nested Div 2 content
</div>
<div class="nested-div">
Nested Div 3 content
</div>
</div>
</div>
</body>
</html>
*/
@main def Main =
val existingHtml = "<div id='container'><p>This is existing content</p></div>"
val doc: Document = Jsoup.parse(existingHtml)
val nestedDiv1: Element = doc.createElement("div")
nestedDiv1.attr("class", "nested-div")
nestedDiv1.text("Nested Div 1 content")
val nestedDiv2: Element = doc.createElement("div")
nestedDiv2.attr("class", "nested-div")
nestedDiv2.text("Nested Div 2 content")
val nestedDiv3: Element = doc.createElement("div")
nestedDiv3.attr("class", "nested-div")
nestedDiv3.text("Nested Div 3 content")
nestedDiv1.appendChild(nestedDiv2)
nestedDiv1.appendChild(nestedDiv3)
val containerDiv: Element = doc.getElementById("container")
containerDiv.appendChild(nestedDiv1)
val modifiedHtml: String = doc.outerHtml()
println(modifiedHtml)
To create the table of contents here I need to nest multiple DIVs inside each other, and I just needed some working sample code like this to get myself going.