![](/img/trans.png)
[英]How to add name attribute of input field dynamically using Javascript/Jquery
[英]How to add an attribute dynamically using javascript
我想使用id获得一个元素:
var a = document.getElementById("hello");
然后向其动态添加一个名为“ labelText”的属性,并为其分配值“ {labeltext}”。
我需要使用串联吗?
我尝试了以下操作,但没有成功:
document.getElementById("hello").setAttribute("labelText", "'{' + labelText + '}' ");
您所做的工作基本上可以正常工作,首先由Vohuman明确识别出语法错误。
//Assign the Attribute: var labelText='Some Value'; document.getElementById("hello").setAttribute('labelText', '{' + labelText + '}' ); //Define some variables for getting the results var attributeEl = document.getElementById("attribute"); var theHTMLEl = document.getElementById("theHTML"); ///Get the attribute value var textLabelValue = document.getElementById("hello").getAttribute('labelText'); //Show the results: attributeEl.textContent = textLabelValue; theHTMLEl.textContent = document.getElementById("hello").outerHTML;
<div id="hello"></div> The labelText attribute is: <div id="attribute"></div> The resulting HTML is: <div id="theHTML"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.