See this example.
<!DOCTYPE html>
<html>
<head>
<style>
ul, p, input { font-size: 18px; }
ul {
list-style:none;
padding:0px;
margin:0px;
}
ul li {
display:block;
position:relative;
float:left;
border:none;
}
li ul {
display:none;
}
ul li a {
display:block;
transition:all linear 0.2s;
background:#000;
padding:5px 10px;
text-decoration:none;
white-space:nowrap;
color:#FFF;
background:#909EAB;
}
ul li a:hover {
background:#4B545F;
}
li:hover ul {
display:block;
position:absolute;
}
li:hover li {
float:none;
}
li:hover a {
background:#5F6975;
}
li:hover li a:hover {
background:#4B545F;
}
</style>
</head>
<body>
<h2>Click the button to create a beatiful dropdown menu using dynamic XML data.</h2>
<p>
XML data is extracted from a remote file using async and await methods in JavaScript.
</p>
<p>
<input type='button' onclick='get_data()' value='Create a Menu' />
</p>
<ul id="menu1"></ul>
</body>
<script>
// using async and await to fetch xml data.
let get_data = async() => {
let url = "../../library/library.xml"; // the XML file.
let response = await fetch (url);
const xmlData = await response.text().then(( str ) => {
return new DOMParser().parseFromString(str, 'application/xml');
});
createMenu(xmlData); // convert data to a dropdown menu.
}
let createMenu = (xml) => {
// the xml tag name
let ucBooks = xml.getElementsByTagName('List');
let arr = [];
for (let i = 0; i < ucBooks.length; i++)
{
// Push XML attributes into the array.
arr.push({
Name: ucBooks[i].getElementsByTagName('BookName')
});
}
let li = document.createElement('li');
let a = document.createElement('a');
a.setAttribute ('href', '#');
a.innerHTML = 'Books'; // the top menu.
li.appendChild(a);
document.getElementById('menu1').innerHTML = '';
document.getElementById('menu1').appendChild(li);
// Create sub ul.
const sub_ul = document.createElement('ul');
li.appendChild(sub_ul);
for (let i = 0; i < arr.length; i++) {
const sub_li = document.createElement('li');
const a_menu = document.createElement('a');
a_menu.setAttribute ('href', 'https://www.encodedna.com');
a_menu.innerHTML = arr[i].Name[0].childNodes[0].nodeValue;
sub_li.appendChild(a_menu);
sub_ul.appendChild(sub_li);
}
}
</script>
</html>