I'm wondering how with javascript can I target a ul within a div, to use javascript to add another li to the ul. The problem is that the div has an id, the ul, and subsequent li's do not.
HTML:
<div id="topnav">
<div id="navcontainer">
<ul>
<li><a href="./" rel="">Hello |</a></li>
<li><a href="services.php" rel="" id="current">We Provide |</a></li>
<li><a href="service_providers.php" rel="">Service Providers</a></li>
</ul>
Ordinarily I would just add an id to the ul, but I with the software I'm using that is not an option, I must use javascript to acplish this task. Thanks in Advance!
I'm wondering how with javascript can I target a ul within a div, to use javascript to add another li to the ul. The problem is that the div has an id, the ul, and subsequent li's do not.
HTML:
<div id="topnav">
<div id="navcontainer">
<ul>
<li><a href="./" rel="">Hello |</a></li>
<li><a href="services.php" rel="" id="current">We Provide |</a></li>
<li><a href="service_providers.php" rel="">Service Providers</a></li>
</ul>
Ordinarily I would just add an id to the ul, but I with the software I'm using that is not an option, I must use javascript to acplish this task. Thanks in Advance!
Share Improve this question asked May 12, 2016 at 17:43 Spencer DavisSpencer Davis 372 silver badges7 bronze badges2 Answers
Reset to default 4try using querySelector
var ulElement = document.querySelector( "#navcontainer ul" )
var myList = document.getElementById('navcontainer').getElementsByTagName('ul')[0];
// or: var myList = document.querySelector('#navcontainer ul');
var myNewListItem = document.createElement('li');
myNewListItem.textContent = "A New Item";
myList.appendChild(myNewListItem);