Create a <p> element, and add in Javascript

Javascript HTML

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

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

Details on how to add elements are below.

Create an <p> 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 selector (id="id_for_p" in this case).

<div id="id_for_p">
</div>
// Get element with specified id
var element_id = document.querySelector('#id_for_p');

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

// add <p> element inside the element with selector
element_id.appendChild(element);

Execution result

This code added a <p> element to the html element.

<!-- Execution result -->
<div id="id_for_p">
    <p>text</p>
</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

コメント

タイトルとURLをコピーしました