[英]documentCreatElement(div) returns undefined when I try to select it's attribute
Now am trying to retrieve the elements with the getElementbyId() function but it's returning undefined.现在我正在尝试使用 getElementbyId() function 检索元素,但它返回未定义。 My code looks like this:
我的代码如下所示:
//initially //最初
var contact= document.createElement('div'); var contact= document.createElement('div'); contact.setAttribute('id','contact-grid');
contact.setAttribute('id','contact-grid');
//later on //稍后的
var to=document.getElementById('contact-grid')` to.onclick=function(){ alert('contact clicked'); var to=document.getElementById('contact-grid')` to.onclick=function(){ alert('contact clicked'); }
}
//The code above is not working Console says: I cannot set onclick of undefined. //上面的代码不起作用控制台说:我不能设置未定义的onclick。 Please kindly tell me what AI am doing wrong
请告诉我AI做错了什么
In order to dynamically create and append elements we have to use below methods to achieve what we need.为了动态创建和 append 元素,我们必须使用以下方法来实现我们需要的。 The GetElemenetById function is applicable only if you have applied the appended the newly created element.
GetElemenetById function 仅在您应用了附加的新创建元素时才适用。
document.createElement()
- This method creates the HTML element with the tag name passed as parameter. document.createElement()
- 此方法创建 HTML 元素,标签名称作为参数传递。 example :create a li
element:-示例:创建一个
li
元素:-
var dynamicLi = document.createElement("li");
element.setAttribute()
- This method is use to set attribute. element.setAttribute()
- 此方法用于设置属性。 example - add id
in the newly create li
tag":-示例- 在新创建的
li
标签中add id
":-
dynamicLI.setAttribute("id","li1");
node.appendChild()
- This method append a node to the end of the list of children of a specified parent node. node.appendChild()
- 这个方法 append 一个节点到指定父节点的子节点列表的末尾。 example - add newly created li tag
to its parent ul tag
:-示例- 将新创建的
li tag
到parent ul tag
:-
let ul = document.getElementById("dynamic-list"); // we get the parent node ul.appendChild(li); // we append the li in the ul tag.
So, below is the working code snippet, using step defined above:因此,下面是工作代码片段,使用上面定义的步骤:
let ul = document.getElementById("Ul");
let li = document.createElement("li");
li.setAttribute('id','li1');
ul.appendChild(li);
let newlyElem =document.getElementById("li1"); //code to find newly created element by element by id after append child.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.