How to add tags inside a div

Hello! In the code below i successfully retrieve the div#links element but don’t know how I can add a tag elements inside the div.

Here is my code so far

const links_arr = {
  "portfolio": "https://portfolio.io",
  "github": "https://github.com/username",
  "linkedin": "https://www.linkedin.com/in/username"
}

const static_url = "https://static-links-page.signalnerve.workers.dev"
addEventListener("fetch", event => {
  return event.respondWith(
    handleRequest(event.request)
  )
})

class LinksTransformer {
  constructor(links) {
    this.links = links
    console.log("in constructor!");
  }

  element(element) {
    // element handler
    console.log(element.tagName)
  }
}

function handleJSON(req){
  let link_str = JSON.stringify(links_arr, null, 2)
  return new Response(link_str, {
    headers: {
      "content-type": "application/json;charset=UTF-8"
    }
  })
}

async function handleRequest(request) {
  let url_split = request.url.split("/")

  switch(url_split[3]){

    case "link":
      handleJSON(request)
      break;

    default:
      const res     = await fetch(request)
      const url_res = await fetch(static_url)
      console.log(url_res)

      return new HTMLRewriter()
                 .on("div#links", new LinksTransformer(links_arr))
                 .transform(url_res)
  }
}

And the code I’m trying to achieve

<div id="links">
  <a href="https://asampleurl.com">A sample URL</a>
  <a href="https://anothersampleurl.com">Another sample URL</a>
  <a href="https://afinalsampleurl.com">A final sample URL</a>
</div>

You can insert HTML inside an element using the prepend and append methods on the element value. For this case, you’ll want to append multiple a elements to the element like so:

element(element) {
    for (const [text, link] in Object.entries(this.links)) {
        element.append(`<a href="${link}">${text}</a>`, { html: true })
    }
}

For more info on HTMLRewriter APIs, see the docs.

1 Like