I know how to use JavaScript to add an anchor element to my page, for example
var userName_a = document.createElement('a');
However, now I'd like to add a style name onto that element also, for example I tried
var userName_a = document.createElement('a class="normalLink"');
Which didn't work, and caused my JavaScript to stop running.
Which is the best way to add a style name to an element Iv'e created using JavaScript?
I know how to use JavaScript to add an anchor element to my page, for example
var userName_a = document.createElement('a');
However, now I'd like to add a style name onto that element also, for example I tried
var userName_a = document.createElement('a class="normalLink"');
Which didn't work, and caused my JavaScript to stop running.
Which is the best way to add a style name to an element Iv'e created using JavaScript?
Share Improve this question edited Dec 5, 2018 at 13:28 shawty 5,8392 gold badges42 silver badges72 bronze badges asked Jan 26, 2016 at 2:50 TomTom 8431 gold badge9 silver badges30 bronze badges 1-
2
after you've created it, do something like
userName_a.className = 'normalLink';
to add a class - but if you want to add STYLE as you asked, useuserName_a.style
for exampleuserName_a.style.background = 'red';
oruserName_a.style.cssText = 'color:blue; width:40px; height:20px;';
– Jaromanda X Commented Jan 26, 2016 at 2:52
4 Answers
Reset to default 2The createElement function takes only the name of the HTML tag you wish to create, nothing else.
You access the style(s) of an element by using style property, or adding/removing style classes either through the className, or classList list
Style property
userName_a.style.background = "#FF0000";
userName_a.style["font-size"] = "20px";
className
userName_a.className = "active";
classList
userName_a.classList.add("active");
userName_a.classList.remove("active");
userName_a.classList.toggle("active");
like this
var userName_a = document.createElement('a');
document.body.appendChild(userName_a);
userName_a.innerHTML='HELLO WORLD';
userName_a.style='color:red;background:yellow'
The most consistent way is to use the setAttribute function:
var userName_a = document.createElement('a');
userName_a.setAttribute( 'class', 'normalLink' );
userName_a.setAttribute( 'style', 'color:blue;font-weight:bold;' );
Since it looks like you just want to have a class name on the object, the simplest way to do that is to just assign a class name to the object after you create it:
var userName_a = document.createElement('a');
userName_a.className = "normalLink";
You can also just modify the style property directly too:
userName_a.style.color = "red";
userName_a.style.textDecoration = "none";