最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to target a ul within a div using Javascript - Stack Overflow

programmeradmin5浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

try 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);
发布评论

评论列表(0)

  1. 暂无评论