[英]How can I add a style class name onto my anchor element using JavaScript
I know how to use JavaScript to add an anchor element to my page, for example 例如,我知道如何使用JavaScript向页面添加锚元素
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. 哪个无效,并导致我的JavaScript停止运行。
Which is the best way to add a style name to an element Iv'e created using JavaScript? 在使用JavaScript创建的元素中添加样式名称的最佳方法是哪种?
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 createElement function takes only the name of the HTML tag you wish to create, nothing else. createElement函数仅采用您要创建的HTML标记的名称,而没有其他名称。
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属性或通过className或classList列表添加/删除样式类来访问元素的样式
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");
The most consistent way is to use the setAttribute function: 最一致的方法是使用setAttribute函数:
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: 您也可以直接直接修改style属性:
userName_a.style.color = "red";
userName_a.style.textDecoration = "none";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.