I want to insert some unknown HTML (contentToInsert) and remove it later at some point.
If I use insertAdjacentHTML, I cannot later say
myDiv.insertAdjacentHTML('afterbegin', contentToInsert);
myDiv.querySelector('contentToInsert') //cannot work of course
because this does not have id or classname.
I cannot wrap it like this (so I have reference to it later):
var content = document.createElement('div');
content.classList.add('my-content-wrap')
content.innerHTML = contentToInsert;
myDiv.insertAdjacentHTML('afterbegin', adContent);//it can be any allowed position, not just afterbegin
Basically I want to remove it later at some point but dont know how to select it. I dont know the position in which this is going to be instered.
Since insertAdjacentHTML only accepts a string you can
Define your content as a string
Use a template/string to add it
Add that string to myDiv.
Then you can target myDiv again with a selector pointed at that element with the my-content-wrap class, and remove it from the DOM.
const myDiv = document.querySelector('#myDiv');
const content = 'Disappears after two seconds';
const html = `<div class="my-content-wrap">${content}</div>`;
myDiv.insertAdjacentHTML('afterbegin', html);
const pickup = myDiv.querySelector('.my-content-wrap');
setTimeout(() => pickup.remove(), 2000);
<div id="myDiv">Original content</div>
You said "I want to insert some unknown HTML (contentToInsert) and remove it later at some point"
I wouldn't use insertAdjacentHTML at all. Here's how you can achieve it:
let myDiv = document.getElementById('myDiv');
let contentToInsert = "<h1>Some html content</h1>";
myDiv.innerHTML = contentToInsert;
This will insert your content into your div. And you can remove it with:
myDiv.innerHTML = "";
in one of the cases...
const
divElm = document.querySelector('#div-elm')
, Insert_1 = '<span>inserted content 1 </span>'
, Insert_2 = '<span>inserted content 2 </span>'
;
divElm.insertAdjacentHTML('afterbegin', Insert_1);
const ref_1 = divElm.firstChild;
divElm.insertAdjacentHTML('afterbegin', Insert_2);
const ref_2 = divElm.firstChild;
ref_1.classList.add('RED')
ref_2.classList.add('BLU')
console.log( '', ref_1, `\n`, ref_2 )
.RED { color: red; }
.BLU { color: blue; }
<div id="div-elm">
blah blah bla..
</div>
many amazing people already answered your question but here's a workaround, if you're only Adding this specific html using js and other content is preadded in html it's always gonna be the first child as you're using afterbegin or else you can do it like others gave you examples.
Sorry can't comment not enough reputation and recently joined
Related
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 MDN)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);
// Create, but don't inject
// ------------------------
const virtual = Object.assign(
document.createElement(`p`),
{ innerHTML: `
id1
<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
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 MDN)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);
// Create, but don't inject
// ------------------------
const virtual = Object.assign(
document.createElement(`p`),
{ innerHTML: `
id1
<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
What I do is I use XMLHttpRequest() to load plain text into a div's innerHTML..
The online text file contains something like this:
<div class="a_class" id="a_id">Text</div>
My html already contains a class like ".a_class" and what I load, it applies the style perfectly to it.
But I can't use Javascript to change the loaded elements, is there a way to style the loaded elements by Id or Class? When I change all elements by class, those having that class wont change..
It works now! I just made sure that the script runs after loading completes..
You can insert the raw html into a temporary element in memory and manipulate it there before inserting in the DOM
const fakeFetch = () =>{
return new Promise(res=> res('<div class="a_class" id="a_id">Text</div>'))
}
fakeFetch().then(html => {
const temp = document.createElement('div');
temp.innerHTML = html;
temp.querySelectorAll('.a_class').forEach(el => el.classList.remove('a_class'))
const res = temp.innerHTML;
document.querySelector('#container').innerHTML += res
console.log(res)
})
.a_class{color:red}
<div id="container"></div>
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 MDN)`})
);
document.querySelector(`#myBrandnewDiv2`).appendChild(fragment);
// Create, but don't inject
// ------------------------
const virtual = Object.assign(
document.createElement(`p`),
{ innerHTML: `
id1
<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
How do I add a class for the div?
var new_row = document.createElement('div');
This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.
new_row.className = "aClassName";
Here's more information on MDN: className
Use the .classList.add() method:
const element = document.querySelector('div.foo');
element.classList.add('bar');
console.log(element.className);
<div class="foo"></div>
This method is better than overwriting the className property, because it doesn't remove other classes and doesn't add the class if the element already has it.
You can also toggle or remove classes using element.classList (see the MDN documentation).
Here is working source code using a function approach.
<html>
<head>
<style>
.news{padding:10px; margin-top:2px;background-color:red;color:#fff;}
</style>
</head>
<body>
<div id="dd"></div>
<script>
(function(){
var countup = this;
var newNode = document.createElement('div');
newNode.className = 'textNode news content';
newNode.innerHTML = 'this created div contains a class while created!!!';
document.getElementById('dd').appendChild(newNode);
})();
</script>
</body>
</html>
3 ways to add a class to a DOM element in JavaScript
There are multiple ways of doing this. I will show you three ways to add classes and clarify some benefits of each way.
You can use any given method to add a class to your element, another way to check for, change or remove them.
The className way - Simple way to add a single or multiple classes and remove or change all classes.
The classList way - The way to manipulate classes; add, change or remove a single or multiple classes at the same time. They can easily be changed at any time in your code.
The DOM way - When writing code according to the DOM model, this gives a cleaner code and functions similar to the className way.
The className way
This is the simple way, storing all classes in a string. The string can easily be changed or appended.
// Create a div and add a class
var new_row = document.createElement("div");
new_row.className = "aClassName";
// Add another class. A space ' ' separates class names
new_row.className = "aClassName anotherClass";
// Another way of appending classes
new_row.className = new_row.className + " yetAClass";
If an element has a single class, checking for it is simple:
// Checking an element with a single class
new_row.className == "aClassName" ;
if ( new_row.className == "aClassName" )
// true
Removing all classes or changing them is very easy
// Changing all classes
new_row.className = "newClass";
// Removing all classes
new_row.className = "";
Searching for or removing a single class when multiple classes are used is difficult. You need to split the className string into an array, search them through one by one, remove the one you need and add all others back to your element. The classList way addresses this problem and can be used even if the class was set the className way.
The classList way
It is easy to manipulate classes when you need to. You can add, remove or check for them as you wish! It can be used with single or multiple classes.
// Create a div and add a class
var new_row = document.createElement("div");
new_row.classList.add( "aClassName" );
// Add another class
new_row.classList.add( "anotherClass" );
// Add multiple classes
new_row.classList.add( "yetAClass", "moreClasses", "anyClass" );
// Check for a class
if ( new_row.classList.contains( "anotherClass" ) )
// true
// Remove a class or multiple classes
new_row.classList.remove( "anyClass" );
new_row.classList.remove( "yetAClass", "moreClasses" );
// Replace a class
new_row.classList.replace( "anotherClass", "newClass" );
// Toggle a class - add it if it does not exist or remove it if it exists
new_row.classList.toggle( "visible" );
Removing all classes or changing to a single class is easier done the className way.
The DOM way
If you write code the DOM way, this looks cleaner and stores classes in a string by setting the class attribute.
// Create a div, add it to the documet and set class
var new_row = document.createElement( "div" );
document.body.appendChild( new_row );
new_row.setAttribute( "class", "aClassName anotherClass" );
// Add some text
new_row.appendChild( document.createTextNode( "Some text" ) );
// Remove all classes
new_row.removeAttribute( "class" );
Checking for a class is simple, when a single class is being used
// Checking when a single class is used
if ( new_row.hasAttribute( "class" )
&& new_row.getAttribute( "class" ) == "anotherClass" )
// true
Checking for or removing a single class when multiple classes are used uses the same approach as the className way. But the classList way is easier to accomplish this and can be used, even if you set it the DOM way.
If doing a lot of element creations, you can create your own basic createElementWithClass function.
function createElementWithClass(type, className) {
const element = document.createElement(type);
element.className = className
return element;
}
Very basic I know, but being able to call the following is less cluttering.
const myDiv = createElementWithClass('div', 'some-class')
as opposed to a lot of
const element1 = document.createElement('div');
element.className = 'a-class-name'
over and over.
If you want to create multiple elements all with in one method.
function createElement(el, options, listen = [], appendTo){
let element = document.createElement(el);
Object.keys(options).forEach(function (k){
element[k] = options[k];
});
if(listen.length > 0){
listen.forEach(function(l){
element.addEventListener(l.event, l.f);
});
}
appendTo.append(element);
}
let main = document.getElementById('addHere');
createElement('button', {id: 'myBtn', className: 'btn btn-primary', textContent: 'Add Alert'}, [{
event: 'click',
f: function(){
createElement('div', {className: 'alert alert-success mt-2', textContent: 'Working' }, [], main);
}
}], main);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div id="addHere" class="text-center mt-2"></div>
var newItem = document.createElement('div');
newItem.style = ('background-color:red');
newItem.className = ('new_class');
newItem.innerHTML = ('<img src="./profitly_files/TimCover1_bigger.jpg" width=50 height=50> some long text with ticker $DDSSD');
var list = document.getElementById('x-auto-1');
list.insertBefore(newItem, list.childNodes[0]);
Cross-browser solution
Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:
function addClass(id,classname) {
var element, name, arr;
element = document.getElementById(id);
arr = element.className.split(" ");
if (arr.indexOf(classname) == -1) { // check if class is already added
element.className += " " + classname;
}
}
addClass('div1','show')
Source: how to js add class
var new_row = document.createElement('div');
new_row.setAttribute("class", "YOUR_CLASS");
This will work ;-)
source
It is also worth taking a look at:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
If you want to create a new input field with for example file type:
// Create a new Input with type file and id='file-input'
var newFileInput = document.createElement('input');
// The new input file will have type 'file'
newFileInput.type = "file";
// The new input file will have class="w-95 mb-1" (width - 95%, margin-bottom: .25rem)
newFileInput.className = "w-95 mb-1"
The output will be: <input type="file" class="w-95 mb-1">
If you want to create a nested tag using JavaScript, the simplest way is with innerHtml:
var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';
The output will be:
<li>
<span class="toggle">Jan</span>
</li>
<script>
document.getElementById('add-Box').addEventListener('click', function (event) {
let itemParent = document.getElementById('box-Parent');
let newItem = document.createElement('li');
newItem.className = 'box';
itemParent.appendChild(newItem);
})
</script>