Matthew C
Matthew C

Reputation: 35

Jquery no effect on element added with replaceWith

I am using replaceWith to add a common navigation bar to multiple pages.

After the replaceWith() I want to add the "active" class to one of the li elements to make the link seem active.

The code has no effect on runtime. But when I run $("#link1").addClass("active") afterwards in Chrome Snippets it works as expected.

<body>
<div id='nav-placeholder'></div>

<script>
        $.get("static/html/navbar.html", function(data){
          $("#nav-placeholder").replaceWith(data);
        });
        //There is an <li> element in navbar.html with id="link1"
        $("#link1").addClass("active");
</script>
</body>

Upvotes: 0

Views: 148

Answers (2)

Pranay Kumar
Pranay Kumar

Reputation: 2267

<div id='nav-placeholder'></div>

<script>
        $.get("static/html/navbar.html", function(data){
          $("#nav-placeholder").replaceWith(data);
          $("#link1").addClass("active");
        });        
</script>

Upvotes: 1

Pablo R. Dinella
Pablo R. Dinella

Reputation: 790

Try chaining the jQuery methods like this:

<body>
<div id='nav-placeholder'></div>

<script>
        $.get("static/html/navbar.html", function(data){
          $("#nav-placeholder").replaceWith(data).find("#link1").addClass("active");
        });
</script>
</body>

Upvotes: 0

Related Questions