document.createElement('div') with a class
Do div.classList.add
let div = document.createElement('div');div.classList.add('test');let text = document.createTextNode('Test');div.appendChild(text);document.body.appendChild(div)
.test { color: green;}
How can I add a class to a DOM element in JavaScript?
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
Create element and assign class in one step
Although the usual way to do it is a two-step technique, try this:
const el = Object.assign(document.createElement('div'), { className: 'foo' });
console.log(el);
console.log(el.className);
How to put a div into the document when that element and its class name are dynamically created (e.g. document.createElement)?
eParent
needs to be DOM Element
that exists. For example, you could call document.querySelector('body')
and get the body, which would then allow you to append to the body
element.
It's difficult to give you a direct solution without seeing the HTML
structure. But in short, the parent element you want to append to needs to be inside the querySelector
function.
How to add class to element created using document.createElement?
before append li tag in the ul you need add your class then append li tag to ul tag like this
var listItem = document.createElement('LI');
listItem.className = 'someClassName';
ul.appendChild(listItem);
Add ID/class to objects from createElement method
One way with Javascript, is by using setAttribute:
element.setAttribute(name, value);
Example:
var btn=document.createElement("BUTTON");
btn.setAttribute("id", "btn_id");
btn.setAttribute("class", "btn_class");
btn.setAttribute("width", "250px");
btn.setAttribute("data-comma-delimited-array", "one,two,three,four");
btn.setAttribute("anything-random", document.getElementsByTagName("img").length);
The advantage of this way is that you can assign arbitrary values to arbitrary names.
https://developer.mozilla.org/en-US/docs/Web/API/element.setAttribute
Add class when element is created
If you want to override the behavior of document.createElement
-- really, really want to -- then:
document.createElement = (function() {
var original_createElement = document.createElement.bind(document);
return function(tagName, cls) {
var elt = original_createElement(tagName);
elt.className = cls;
return elt;
};
}());
A couple of notes about this:
We use a IIFE in order to isolate
original_createElement
inside the closure.We need to do the
bind
ondocument.createElement
because that function requires thedocument
context.This function is designed to be used as in
document.createElement('div', 'foo')
. If you really, really wantfoo
to be added to every single element you ever create in the future, then remove thecls
argument and doelt.className = 'foo';
instead.
But in any case I don't recommend doing this at all.
Instead, as described in the comments and other answers, define your own functionn:
function createElementWithClassFoo() {
var div = document.createElement('div');
div.classList.add('foo');
return div;
}
Or generalize it to any class:
function createElementWithClass(cls) {
var div = document.createElement('div');
div.classList.add(cls);
return div;
}
Then call
var divElement = createElementWithClassFoo();
var divElement = createElementWithClass('foo');
Create Element with id or class with React Dom
The id
and/or class
of foo
can be specified via the setAttribute(..)
and classList.add(..)
methods as shown:
const foo = document.createElement('div');
/* Set id of "some-id" on foo */
foo.setAttribute("id", "some-id");
/* Add class of "some-class" to foo */
foo.classList.add("some-class");
How to append an element to a div with className that have a child elemnt with idName
you should get all items has class form-group with querySelectorAll
const arrayElement = document.querySelectorAll('.form-group');
for(let i = 0; i < arrayElement.length; i++)
{
const errorMessage = document.createElement('span');
errorMessage.textContent = "invalid input";
arrayElement[i].appendChild(errorMessage);
}
more : https://jsfiddle.net/7znf685q/2/
Related Topics
How to Rotate an Image by a Random Amount Using CSS
What Exactly Is Cdata and What Does It Do
How to Save an Image with CSS Filter Applied
Using !Important in Jquery's CSS() Function
Start a CSS Animation on Button Click
How to Grab the CSS Truncated Text via Jquery
Angularjs Bug in Ie with Style VS Ng-Style
How to Disable Caching of Static Assets Like .CSS and .Js in Jsf2
Provide Local Fallback for CSS from Cdn
Dropdown Checkboxes and Unchecked Parents Element
Grunt Plugin for Assets Versioning
How to Make Cross-Browser CSS3 Code Dry
Style Autofill or Autocomplete Default Browser Dropdown
How to Add an Icon to the Options in React-Select
CSS Media Query Height Greater Than Width and Vice Versa (Or How to Imitate with JavaScript)