skip to Main Content

I have a pure HTML/CSS navigation bar in 4 pages, like this:

<nav id="bar">
<ul id="nav">
<li><a href="aa.html">AA</a></li>
<li><a href="bb.html">BB</a></li>
<li id="page">CC</li>
<li><a href="dd.html">DD</a></li>
</ul>
</nav>

I can get the page name using javascript, with

var pagename = window.location.pathname.split('/').pop();

I want to use Jquery to add the same code to every page, and, depending on the html page, remove the a link and change the id using something like (pseudocode):

$("#nav").append(<li><a href="aa.html">AA</a></li>
<li><a href="bb.html">BB</a></li><li><a href="cc.html">CC</a></li><li><a href="dd.html">DD</a></li>

$("#nav").find(pagename).parent().removelink_and_add_the_"page"_id()

That is, if the current page is DD.html, the navigation bar changes the <li><a href="dd.html">DD</a></li> to <li id="page">DD</li>

Is it posible? Any hint?
Thank you in advance!!

2

Answers


  1. Find the <a> using css attribute selectors:

    let myElem = $("a[href='dd.html']")
    

    Then change the id of the parent, add the DD text to the parent, and finally use .remove() on myElem

    Login or Signup to reply.
  2. //supose pagename is DD.html
    //var pagename = window.location.pathname.split('/').pop();
    var pagename = "dd.html";
    
    $("#nav").append('<li><a href="aa.html">AA</a></li><li><a href="bb.html">BB</a></li><li><a href="cc.html">CC</a></li><li><a href="dd.html">DD</a></li>')
    
    var $aElem = $("#nav").find("a[href='" + pagename + "']");
    //set id and text/html of li parent (if is just text use text() instead html())
    $aElem.parent().attr("id", "page").html($aElem.html());
    //bye a element
    $aElem.remove();
    //checking changes in li element
    console.log($("#page")[0])
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <nav id="nav">
    
    </nav>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search