Create and add <a> element in Javascript

Javascript HTML

First of all, this is the code that creates the <a> element with Javascript and sets the href and text. Please use this by copy-pasteing.

// create <a> element
var element = document.createElement("a");
element.href="URL";
element.textContent="text";

Details on how to add elements are below.

Create an <a> element and add it inside the element with the specified id

This is the code to add the created a element to the element with the specified id (id="id_for_a" in this case).

<div id="id_for_a">
</div>
// Get element with specified id
var element_id = document.getElementById('id_for_a');

// create <a> element
var element = document.createElement("a");
element.href="URL";
element.textContent="text";

// add <a> element inside the element with specified id
element_id.appendChild(element);

Execution result

This code will add an <a> element to your html and the display will look like the image.

<!-- Execution result -->
<div id="id_for_a">
    <a href="URL">text</a>
</div>

Reference document

Related documents on MDN that I used as a reference when writing this article.
Please also see this.

Document.createElement() – Web API | MDN
https://developer.mozilla.org/ja/docs/Web/API/Document/createElement

コメント

Copied title and URL