Skip to content

Trying to append a div to the document using vanilla js

I am trying to append a an element to the document with vanilla JavaScript but it’s giving me this error: “Uncaught DOMException: Failed to execute ‘createElement’ on ‘Document’: The tag name provided (”) is not a valid name.”

This is all my js code:

function newProject(root,img) {
    const project = document.createElement("<div class='element'><a href='" + root +"'><img src='"+ img +"'></a></div>");
    const element = document.querySelector(".projects");
    element.appendChild(project);
}

newProject('../projects/periodic-table/tabla-periodica.html', '../img/tabla-valencias.png');

Answer

document.createElement will only create a single empty element, e.g., <div></div>, and only takes the tag name (div) as a parameter. So you should construct your elements manually like this:

const project = document.createElement('div');
project.className = 'element';

const projectLink = document.createElement('a');
projectLink.href = root;
project.appendChild(projectLink);

const image = document.createElement('img');
image.src = img;
project.appendChild(image);

You can also use .innerHTML to insert HTML content into a node directly, but for dynamic content (i.e., generated by variables, such as in your case). I’d recommend against this as this doesn’t escape the contents of the variables and leaves you vurnerable to XSS attacks on your code.