I am trying to retrieve the ID of an XML element, but I am struggling with accessing it. The element is selected randomly, so I am unsure how to obtain its information.
To give you a better idea of what I am working on, here is a snippet of my code:
I have an XML file containing two pieces of information (a YouTube link and a corresponding ID) structured like this:
<videos>
<video id="0">o6f9wJ1DWhY</video>
<video id="2">sp_WV91jx8E</video>
<video id="3">plWnm7UpsXk</video>
<video id="4">a1Y73sPHKxw</video>
<video id="5">9avT0e5KPPU</video>
<video id="6">VTO5yiN1b-I</video>
<video id="7">HnENgvGFc4</video>
<video id="8">d8u4CEBVq7s</video>
<video id="9">abRplCazEjk</video>
</videos>
In the next step, I extract the data from an external XML file and store it in a variable:
var jqxhr = $.ajax({
type: 'POST',
url: "freeakshow.xml",
dataType: 'xml',
global: false,
async:false,
success: function(data) {
return data;
}
}).responseText;
xml_string = jqxhr;
Then, I use the DOMParser to parse the links into an array for future access:
function get_ids_from_xml_string(xml_string) {
// Parse the XML string into a XMLDocument
var doc = window.DOMParser
? new DOMParser().parseFromString(xml_string, 'text/xml')
: new ActiveXObject('Microsoft.XMLDOM').loadXML(xml_string);
// Locate the video nodes
var id_nodes = doc.getElementsByTagName('video');
var videos = [];
// Store their text content in an array
for (var i = 0; i < id_nodes.length; i++) {
videos.push(id_nodes[i].firstChild.data)
}
return videos;
}
var videos = get_ids_from_xml_string(xml_string);
Next, I select a random link from the array to be used with the YouTube API, although that's not relevant at the moment:
function getId() {
return videos[Math.floor(Math.random() * videos.length)];
Now, here comes the question: How can I retrieve the ID of the current random link obtained from getId()?
I aim to display it within a div to keep track of the current and previous IDs of the randomly playing videos.
(In simple terms, I want to showcase which ID is currently being played and which one was played last)