0

Is this behaviour normal when creating a link with document.createElement("a") ?

function updateUl(newVal){
    let a = document.createElement("a")
    let newListItem = document.createElement("li")

    a.appendChild(document.createTextNode(newVal))
    console.log(newVal) //output: "www.google.com"
    a.href = newVal
    console.log(a.href) //output: "http://127.0.0.1:5500/www.google.com"
    a.target = "_blank"
    newListItem.appendChild(a)
    ulEl.appendChild(newListItem)
}

Then clearly when I click on the link I get a page not found error.

What's going on?

IDK
  • 359
  • 1
  • 16
  • The `href` property setter is relative by default. `www.google.com` is a path-relative URL. Try an absolute URL instead: `"https://www.google.com"` or a protocol-relative one: `"//www.google.com"`. – Sebastian Simon Mar 04 '22 at 18:36

1 Answers1

1

Without a protocol, it's assumed to be a route on the current page. Add the https:// protocol to make it navigate.

function updateUl(newVal){ // pass in as "https://www.google.com"
    let a = document.createElement("a")
    let newListItem = document.createElement("li")

    a.appendChild(document.createTextNode(newVal))
    console.log(newVal) //output: "https://www.google.com"
    a.href = newVal
    console.log(a.href) //output: "https://www.google.com"
    a.target = "_blank"
    newListItem.appendChild(a)
    ulEl.appendChild(newListItem)
}

or add it dynamically

function updateUl(newVal){
    if (!newVal.startsWith("http://") && !newVal.startsWith("https://") {
        newVal = `https://{newVal}`;
    }
    let a = document.createElement("a")
    let newListItem = document.createElement("li")

    a.appendChild(document.createTextNode(newVal))
    console.log(newVal) //output: "https://www.google.com"
    a.href = newVal
    console.log(a.href) //output: "https://www.google.com"
    a.target = "_blank"
    newListItem.appendChild(a)
    ulEl.appendChild(newListItem)
}
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34