skip to Main Content

Here i created the file brand.html and another file name as nev.js in brand.html file content –

<div class="nev" id="nevbar"></div>
<div class="footer">www.logo.com</div>
<script src="nev.js"></script>

and in nev.js file content –

const nevbarContainer = document.getElementById("nevbar");

    const nevbar = document.createElement("nav");
    const nevbarList = document.createElement("ul");

    const homeLink = document.createElement("li");
    const homeLinkAnchor = document.createElement("a");

    homeLinkAnchor.href = '#';
    homeLinkAnchor.textContent = "Brand";
    homeLink.appendChild(homeLinkAnchor);

    const aboutLink = document.createElement("li");
    const aboutLinkAnchor = document.createElement("a");

    aboutLinkAnchor.href = '#';
    aboutLinkAnchor.textContent = "About";
    aboutLink.appendChild(aboutLinkAnchor);

    const contactLink = document.createElement("li");
    const contactLinkAnchor = document.createElement("a");

    contactLinkAnchor.href = '#';
    contactLinkAnchor.textContent = "Contact";
    contactLink.appendChild(contactLinkAnchor);

    nevbarList.appendChild(homeLink);
    nevbarList.appendChild(aboutLink);
    nevbarList.appendChild(contactLink);

    nevbarContainer.appendChild(nevbar);

The problem is that it doesn’t show any thing on screen what shoud I do to add navbar throught js

2

Answers


  1. Your code is valid, you just didn’t add ‘nevbarList’ to the page.

    const nevbarContainer = document.getElementById("nevbar");
    
    const nevbar = document.createElement("nav");
    const nevbarList = document.createElement("ul");
    
    const homeLink = document.createElement("li");
    const homeLinkAnchor = document.createElement("a");
    
    homeLinkAnchor.href = '#';
    homeLinkAnchor.textContent = "Brand";
    homeLink.appendChild(homeLinkAnchor);
    
    const aboutLink = document.createElement("li");
    const aboutLinkAnchor = document.createElement("a");
    
    aboutLinkAnchor.href = '#';
    aboutLinkAnchor.textContent = "About";
    aboutLink.appendChild(aboutLinkAnchor);
    
    const contactLink = document.createElement("li");
    const contactLinkAnchor = document.createElement("a");
    
    contactLinkAnchor.href = '#';
    contactLinkAnchor.textContent = "Contact";
    contactLink.appendChild(contactLinkAnchor);
    
    nevbarList.appendChild(homeLink);
    nevbarList.appendChild(aboutLink);
    nevbarList.appendChild(contactLink);
    
    nevbar.appendChild(nevbarList);
    nevbarContainer.appendChild(nevbar);
    <div class="nev" id="nevbar"></div>
    <div class="footer">www.logo.com</div>
    Login or Signup to reply.
  2. You forgot to add this one line:

     nevbar.appendChild(nevbarList);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search