Skip to content
Advertisement

Appendchild to a specific id

I’m new to HTML and CSS and I hope to get some help here :D. I want to create an <a> element at a certain div container with the id navigationPaths, which would be this div container.

<div id="navigationPaths">

This is the part of my javascript code which I want to append to this ID. This is what i already found.

var a = document.createElement('a');
var linkText = document.createTextNode("Path");
a.appendChild(linkText);
a.title = "Path";
a.href = "http://google.com";
document.body.appendChild(a);

The functions I found doesn’t really suit my problem so I hope that someone here knows how this works.

Advertisement

Answer

As a postscript to Phil’s comment, if you didn’t want to faff around creating DOM elements, you could create some fully-formed HTML by inserting an HTML string into the element.

const anchor = '<a title="path" href="http://google.com">Path</a>';
const el = document.querySelector('#navigationPaths');
el.insertAdjacentHTML('beforeend', anchor);
<div id="navigationPaths">New anchor: </div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement