I just can't fathom the logic, perhaps I'm over thinking it!
I need to make sure a script's id
attribute is unique before I append it into the DOM.
Here are some examples to show you what I need:
If in the <head>
element I had 3 child script
elements, like:
<script id="script-0"></script>
<script id="script-1"></script>
<script id="script-2"></script>
I'd want my new script
element to have an id
of "script-3"
If I had 3 child script
elements, like:
<script id="script-0"></script>
<script id="script-2"></script>
<script id="script-3"></script>
I'd want my new script
element to have an id
of "script-1"
or "script-4"
And in this case:
<script id="script-1"></script>
<script id="script-2"></script>
I'd want my new script
element to have an id
of "script-0"
or "script-3"
Just so long as the id
attributes of each script element are unique!
In this scenario, each script
element is actually doing a JSONP request, and therefore, as it's asynchronous, another script
element may be added to the DOM
in the interim and would need it's own unique id
.
After the JSONP request has received a response it is removed from the DOM
, hence the gaps in the id
's, like script-0
, script-1
, script-3
, script-4
and script-6
for example, as the JSONP requests script-2
and script-5
may have received a response and been removed from the DOM
. In this case, I'd like a new script
element to have either the id
script-2
, script-5
or, worst case: script-7
.
I hope this is clear enough!
I just can't work out the logic, any help would be very much appreciated!
Oh, and only vanilla JS; no jQuery etc, thank you!
I promise to post an answer to a question on Stackoverflow for every answer posted in reply to this question! Promise!