There is such a code

<p id='666'></p> <p id='342'></p> 

After loading the page to it, as necessary, added more:

 <p id='3123'></p> 

I tried this option:

 $('p:last').attr("id"); 

but it only works with elements that were already in the DOM

How to track the id of the last element regardless of whether it was originally in the DOM or added after the page was loaded?

  • Why not see the id before adding? - Grundy
  • And at what point do you call the selector? Why are you sure that the item is already on the page? - Alexey Prokopenko

1 answer 1

Let's look at the sequence. You have it going something like this:

  1. The DOM is loaded and the content is there.
  2. Your script is executed, which tries to get the last element of P and read its ID.
  3. After some time in the future, say in an hour (!), Some is executed, for example, an AJAX request and inserts another P into the DOM.

You see, your script from point 2 has already worked for a long time, and it does not know that you want to add something else in an hour.

But we remember that JS can run asynchronously. Those. we can lay in him the possibility of waiting for some event in the future and the reaction to it.

The easiest option is the callback function. If your new P tag is inserted after an AJAX request to the server, then you can connect a success callback and perform your search there. Like that:

 $.ajax({ ... success: function (data) { // здесь какой-то код, который вставляет новый тег P на страницу // а вот в этой точке вы уже точно знаете что // новый тег вставлен и можете вызвать свою функцию readLastTag(); } ... }); function readLastTag () { var last_id = $('p:last').attr("id"); console.log(last_id); } 

Exactly the same callback functions can be added to other possible events, for example, some user actions (such as mouse clicks, etc.)

  • The easiest option is to use the live collection, which getElementsByTagName will return - Grundy