首页 > 解决方案 > 使用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。请建议使用这种方法的解决方案。

标签: javascriptajax

解决方案


您不能拥有多个具有相同 ID 的元素。在这种情况下,一个类会更有意义。因此,而不是document.getElementById使用document.getElementsByClassName,这将返回一个数组HTMLCollection。


推荐阅读