Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

77
Visualizações
document.createElement is not working for anchor tags

I was trying to validate some URLs. I have tried using regex and JavaScript URL constructors as well. But I was specifically trying to solve the task with document.createElement('a'). I am following the codes for the task and it works fine in JSbin. But not working in my local editor. Can anyone explain if document.createElement('a') is valid for anchor tags and why there is a result in JSbin and not in my local editor(it shows some error).

P.S Working new with JavaSCript and DOM Manipulation

HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>test</title>
</head>
<body>
<div id="div"></div>
<script src="test.js"></script
</body>
</html>

JavaScript

function isValidURL(str) {
   var div = document.getElementById('div');
   var a  = document.createElement('a');
   a.href = str;
   a.innerText = "check";
   div.appendChild(a);
   return a.protocol === "http:" || a.protocol === "https:";
}
console.log(isValidURL('file:///Y:/bleh/index.html'));
console.log(isValidURL('https://www.youtube.com/watch?v=iFP-EWO_Q_o'));
console.log(isValidURL('en.wikipedia.org'));

The console results false, true, true accordingly in jsbin. But show error ReferenceError: document is not defined in local editor.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda