Dynamically creating HTML elements using Javascript?
I want to dynamically create some HTML elements (3 html element) and then return this html开发者_开发百科 code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.
function createMyElements(id1,id2,id3){
//create anchor with id1
//create div with id 2
//create xyz with id3
//now return the html code of above created just now
}
How can I do this?
[Edit 2021/10] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked (create some element(s) and retrieve their html code) can be found @ the bottom of the snippet.
// The classic createElement
// -------------------------
// create a paragraph element using document.createElement
const elem = document.createElement(`p`);
elem.id = `myBrandnewDiv1`;
// put in some text
elem.appendChild(document.createTextNode(`My brand new div #1`));
// append some html (for demo, preferrably don't use innerHTML)
elem.innerHTML += ` => created using
<code>document.createElement</code>`;
// append a new paragraph within #myBrandNewDiv1
const nested = elem.appendChild(document.createElement(`p`));
nested.classList.add(`nested`);
// add some text to that
nested.textContent = `I am nested!`;
// the elements are still in memory, now add the
// whole enchillada to the document
document.body.appendChild(elem);
// insertAdjacentHTML
// ------------------
// nest an element within the nested div
nested.insertAdjacentHTML(`afterbegin`,
`<div id="nestedWithin#nested">
This text will appear <i>above</i> the text of
my parent, that being div#nested.
Someone had the nerve to insert me using
<code>insertAdjacentHTML</code>
</div>`);
// Object.assign
// -------------
// Use Object.assign to create an element and
// assign properties/html to it in one go
const newElem = Object.assign(
document.createElement(`div`),
{ id: `myBrandnewDiv2`,
innerHTML: `div#myBrandnewDiv2 signing in.
I was <i>assigned</i> using <code>Object.assign</code>…`});
document.body.appendChild(newElem);
// insertAdjacentElement combined with Object.assign
// -------------------------------------------------
// use the above technique combined with insertAdjacentElement
newElem.insertAdjacentElement(
`beforeend`,
Object.assign(document.createElement(`span`),
{ id: `myBrandnewnested2_nested`,
innerHTML: `<br>Me too! And appended I was
with <code>insertAdjacentElement</code>` })
);
// createDocumentFragment
// ----------------------
// Use a document fragment to create/inject html
const fragment = document.createDocumentFragment();
const mdnLnk = `https://developer.mozilla.org/en-US/` +
`docs/Web/API/Document/createDocumentFragment`;
fragment.appendChild(
Object.assign(
document.createElement(`p`),
{innerHTML: `Regards from <code>createDocumentFragment</code>
(see <a href="${mdnLnk}">MDN</a>)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);
// Create, but don't inject
// ------------------------
const virtual = Object.assign(
document.createElement(`p`),
{ innerHTML: `
<a href="#id1">id1</a>
<div id="id2">Hi!</div>
<p id="id3">Hi 2!</p>`,
classList: [`xyz`], } );
const prepareHtml4Reporting = html =>
html.replace(/</g, `<`)
.replace(/\n\s+/g, `\n`)
.replace(/\n\n/g, `\n`);
document.body.insertAdjacentHTML(
`beforeend`,
`<h3>html only</h3><pre>${
prepareHtml4Reporting(virtual.innerHTML)}</pre>`);
body {
font: normal 12px/15px verdana, arial, sans-serif;
margin: 2rem;
}
code {
background-color: #eee;
}
.nested {
margin-left: 0.7rem;
max-width: 450px;
padding: 5px;
border: 1px solid #ccc;
}
I have used some of these methods in this library (see /src/DOM.js
), with a mechanism for sanitizing html before it is injecting.
Html:
<div id="main"></div>
JavaScript:
var tree = document.createDocumentFragment();
var link = document.createElement("a");
link.setAttribute("id", "id1");
link.setAttribute("href", "http://site.com");
link.appendChild(document.createTextNode("linkText"));
var div = document.createElement("div");
div.setAttribute("id", "id2");
div.appendChild(document.createTextNode("divText"));
tree.appendChild(link);
tree.appendChild(div);
document.getElementById("main").appendChild(tree);
The main reason to use a documentFragment in stead of just adding the elements directly is speed of execution.
At this size it doesn't matter, but when you start adding hundreds of elements, you will appreciate doing it in-memory first :-)
With documentFragment you can construct a whole tree of DOM-elements in-memory and will not afffect the browser DOM untill the last moment.
Otherwise it forces the browser to update for every element, which sometimes can be a real pain to watch.
If you're doing this repeatedly (dynamically creating HTML), you might want to use a more general approach.
If you want to create three unrelated elements, you can do:
var anchor = elem("a", {"id":"id1"});
var div = elem("div", {"id":"id2"});
var xyz = elem("div", {"id":"id3"});
Now, you have three elements. If you want to get the HTML of these (as string), simply do:
var html = anchor.outerHTML + div.outerHTML + xyz.outerHTML;
If you want to have these three in an element (say, div), do:
var div = elem("div", null, [
elem("a", {"id":"id1"}),
elem("div", {"id":"id2"}),
elem("div", {"id":"id3"}),
]);
You can get the HTML with div.outerHTML
, or you can just append it anywhere you want.
To know more about elem()
, visit element.js (GitHub).
I'm adding this answer not for the 8 year old question, but for the future visitors. Hope, it helps.
You can construct the html as a string in one variable like
var html = "";
html += "<a id='" + id1 +"'>link</a>";
html += "<div id='" + id1 +"'>div</div>";
// ... and so on
then you return the variable html
return html;
The better way would be to Import ElementsJS and just reference each element in it.
var root = document.getElementById("root");
var elementdiv = create_element('div',{'class':'divcss'}, root, null);
create_element('h1',{'class':'hellocss'}, elementdiv, "Hello World");
.hellocss {
color : red;
}
.divcss {
background-color : blue;
height: 100px;
position: absolute;
}
<script src="https://elementsjs.blob.core.windows.net/public/create-elements.js"></script>
<body id="root"></body>
For More Details Refer to https://github.com/divyamshu/Elements-JS Well Documented with Example.
Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).
Let us say, you have html-page as "index.html" (calling index_static.html here).
index_static.html
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
<h1> Hello !!! </h1>
</body>
</html>
You can open this file in the browser, to see the desired output.
Now, lets create a javascript equivalent to this. Use online-tool, to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:
dynamic.js
document.write("<!DOCTYPE HTML>");
document.write("<html>");
document.write(" <head>");
document.write(" <title>Test<\/title>");
document.write(" <\/head>");
document.write(" <body>");
document.write(" <h1> Hello !!! <\/h1>");
document.write(" <\/body>");
document.write("<\/html>");
And now, your dynamic version of the static_index.html will be as below:
index_dynamic.html
<script language="JavaScript" src="dynamic.js"></script>
Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).
more info
精彩评论