It would be a lot easier to help you if you showed some HTML context, but if new ones are being added after previous ones, you can find them by class (assuming some combination of the classes on them are unique) or based on where they are in the DOM structure, and use the last one:
var list = document.querySelectorAll("a.listWidgetActionAdd"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
}
Live Example:
var list = document.querySelectorAll("a.listWidgetActionAdd"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
document.body.innerHTML = "<code>last.id = " + last.id + "</code>";
}
<a id="document_create:nxl_item:nxw_referenceHeaderList:0:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:1:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:2:nxw...." class="button smallButton listWidgetActionAdd"></a>
Re your comment:
I should've mentioned this earlier that there's another add button within the field that's being created that has a similar class. Is there any way to distinguish them both? Like using a string RegExp? The difference is that the id names are different... Would that help?
If it's just a similar class name, then there's no problem — just use the other class name.
If it's the same class name, then yes, you can use the id
to differentiate them. For instance, here's the above using an attribute starts with selector to only look at a
elements with an id
that starts with document_create:nxl_item:nxw_referenceHeaderList
:
var list = document.querySelectorAll("a[id^='document_create:nxl_item:nxw_referenceHeaderList']"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
document.body.innerHTML = "<code>last.id = " + last.id + "</code>";
}
var list = document.querySelectorAll("a[id^='document_create:nxl_item:nxw_referenceHeaderList']"),
last = list[list.length - 1];
if (last) {
// Use `last`, it's a reference to the element
// `last.id` is its `id` if you need it
document.body.innerHTML = "<code>last.id = " + last.id + "</code>";
}
<a id="document_create:nxl_item:nxw_referenceHeaderList:0:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="some-other-format:0:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:1:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="some-other-format:1:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="document_create:nxl_item:nxw_referenceHeaderList:2:nxw...." class="button smallButton listWidgetActionAdd"></a>
<a id="some-other-format:2:nxw...." class="button smallButton listWidgetActionAdd"></a>