javascript - 使用JS而不是Jquery获取具有特定ID的最后一个孩子
问题描述
嗨,我希望从具有该 id 的各种元素中获取具有特定 id 的最后一个元素。
这个想法是通过Javascript 而不是 Jquery动态添加新行。我有一个 id为 newrow的 div 。单击添加更多行按钮时,我想使用以下代码通过 javascript 和 ajax 附加同一行的副本:
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (this.readyState==4 && this.status==200)
{
//In the following line, I need to get the last newrow element and add new row in it.
//responsetext will have another div with id newrow so that another new row can be added to it.
document.getElementById("newrow").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","newrowcode.php",true);
xmlhttp.send();
我知道这些东西可以与 Jquery 解决方案一起使用,但是我们在这里使用普通的 javascript 进行 ajax。请建议使用这种方法的解决方案。
解决方案
您不能拥有多个具有相同 ID 的元素。在这种情况下,一个类会更有意义。因此,而不是document.getElementById
使用document.getElementsByClassName
,这将返回一个数组HTMLCollection。
推荐阅读
- r - 从模拟数据中分离两个类
- javascript - 如何从 `.txt` 或 `.css` 文件中获取 html 中选项标签中的数据?
- javascript - JS 跳过第一个事件的 if 语句
- dependencies - .deb 取决于间隔
- python - 如何规范化非均匀 Python 数据帧
- php - 在 Laravel 中获取 allDirectories() 并创建一棵树
- python - 获取其他列中唯一值的最大值行:python
- node.js - 为 2FA 实施生成恢复代码
- assembly - AT&T asm ascii 整数转换
- python - 在 Django 中迁移时自动生成表中的数据