开发者

Is there a way to find the ID of the LAST element within a DIV using Javascript?

I think I need to find the id of the last element in my div so that I can append a ul element after it using javascript. The reason for this is that the existing/last ul in my div is generated dyna开发者_如何学编程mically so its id could be anything.

I have tried simply appending the element to the div container using the following code, expecting it to put it at the end..

var container = document.getElementById("container");
var newUL = document.createElement("ul");
container.appendChild(newUL);
newUL.innerHTML = 'Hello';

But this for some reason appends the new ul outside of my div container. Does anyone know why this happens? but also how to find the last element's id so that I can append it after the last element? Thanks.


container.lastElementChild.id 

But I think you need to find the real problem. An UL can't contain text. It may only contain li-elements.


The easiest way would be to rely on a Javascript framework such as jQuery to tackle this problem.

jQuery allow you to answer your situation with this simple code:

$('#container').append(
  $('<ul></ul>').text('Hello')
);

EDIT: Took into account arnaud576875's comment.


You are setting the innerHTML of a ul element to a simple string : 'Hello'; that contravenes the rules. Perhaps a better test would be to add some li elements :

newUl.innerHTML = "<li>One</li><li>Two</li>";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜