Element was removed upon clicking only once

Can anyone help me figure out why the behavior of .remove() with $postNav.remove(); is different here? When you click on "I'm a tag" for the first time, both the <li> and <ol> are deleted as expected. However, on the second click, only the <li> gets deleted and not the <ol>. The HTML remains the same so I'm confused about this inconsistency...

(function($) {
$doc = $(document);
  
  var $container        = $('#main');
  var $pagePosts    = $container.find('div.post_list_wrapper ul');
var $containerNav = $('section.section_things'); 
var $postNav  = $('ol.pagenation');
var $catName    = "";
var $name    = "";
var $page  = "1";
var $clickTag  = "";


$doc.ready( function() {   
  
 
 $("a[rel='tag']").addClass("ajax_tag");

function get_posts(){
  
  $pagePosts.empty();
  $postNav.remove();
        $pagePosts.html("<li>Click Im a tag and scroll down you will see the ol stacking " + $page + "</li><div class='tag'><a rel='tag' href='/things/tag/xxxx/'>I'm a tag</a></div>");
  $containerNav.append("<ol class='pagenation'><a href='#' rel='tag'>" + $page + "Im the new ol</a></ol>");
              $page++;
  
   $("a[rel='tag']").addClass("ajax_tag");
 
} //Get posts
$container.on('click', "a[rel='tag'], .pagination a", function(event) {
$this = $(this);
event.preventDefault();
      
if ($this.hasClass('ajax_tag')) {
$clickTag = $this.text();
} else {
$page = parseInt($this.attr('href').replace(/\D/g,''));
}
get_posts();

}); //onClick
   }); //Anonymous function
})(jQuery); //main function
@charset "UTF-8";
* {
box-sizing: border-box;
}
body, html {
  text-align: center;
}

li {
list-style: none;
}

/* THINGS ========================== */

.top .things .post_profile .category_label {
padding: 9px 20px 5px;
margin-right: 18px;
background-color: #AE965C;
}


/* Pagenation ========================= */
.pagenation {
  text-align: center;
}
.pagenation li {
  display: inline-block;
  margin-right: 30px;
}

.pagenation li.prev a,
.pagenation li.next a {
  position: relative;
}
.pagenation li.prev a:before,
.pagenation li.next a:before {
  content: "";
  display: block;
  position: absolute;
  top: 50%;
  width: 12px;
  height: 12px;
  margin-top: -12px;
  border-top: 1px solid #666666;
  border-right: 1px solid #666666;
}
.pagenation li.prev a:before {
  right: 0px;
  margin-right: 20px;
  transform: rotate(-135deg);
}
.pagenation li.next a:before {
  left: 0px;
  margin-left: 20px;
  transform: rotate(45deg);
}
.pagenation li a:hover:before {
  border-top: 1px solid #AAAAAA;
  border-right: 1px solid #AAAAAA;
}

.pagenation li.prev a:before {
  margin-right: 10px;
}
.pagenation li.next a:before {
  margin-left: 10px;
}
}

#main > section.section_things {
text-align: left;
}
.section_title {
text-align: center;
}
.category_btn {
margin-bottom: 40px;
}
.category_btn li {
display: inline-block;
margin-right: 30px;
}
.category_btn li:last-child {
margin-right: 0;
}
.category_btn li a {
text-align: center;
display: block;
min-width: 180px;
padding: 6px;
border: 2px solid #AE965C;
}

/* ----------------------------------------------
Post list , unit
---------------------------------------------- */

.post_list_wrapper ul {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
}
.post_list_wrapper li {
//width: 340px;
  margin-bottom: 40px;
  }
.post_list_wrapper li .eyecatch {
position: relative;
}
.post_list_wrapper li .eyecatch .category_label {
position: absolute;
bottom: 0px;
left: 0px;
z-index: 10;
}
.post_list_wrapper li .eyecatch .category_label a {
  display: block;
  text-align: center;
}
.post_list_wrapper li .post_body {
  position: relative;
  padding: 20px;
  min-height: 212px;
}

.post_list_wrapper li .post_body .post_title {
  margin-bottom: 20px;
}
.post_list_wrapper li .post_body .tag {
  position: absolute;
  bottom: 20px;
  right: 20px;
  line-height: 1;
}
@media screen and (max-width:768px) {
.category_btn {
  text-align: center;
  margin: 0 15px 15px;
}
.category_btn li {
  display: block;
  margin-right: 0;
}
.category_btn li a {
  border: none;
}

.post_list_wrapper li {
  margin: 0 auto 40px;
}
.post_list_wrapper li .post_body {
  min-height: inherit;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="mainwrapper">
<main role="main" id="main">
    <section class="section_things">
      <h1 class="section_title">Things</h1>
      <ul class="category_btn futura">
        <li class="is_active"><a href="#">ALL</a></li>
      </ul>
<div class="post_list_wrapper">
        <ul>
          <li>
            <div class="eyecatch">
              <a href="/things/things-post.html"><img src="http://placehold.it/340x30"></a>

              <span class="category_label"><a href="/category/xxxxx/">SPECIAL</a></span>
            </div>
            <div class="post_body">
              <a href="/things/things-post.html">
                   
 
                <div class="date">
                  <time datetime="2016-10-26">2016.10.26</time>
                </div>
                <h2 class="post_title">I'm a title</h2>
              </a>
              <div class="tag"><a rel='tag' href="/things/tag/xxxx/">I'm a tag</a></div>
            </div>
          </li>
        </ul>
      </div>
    <ol class="pagenation">
        <li class="prev"><a href="#"></a></li>
        <li class="is_active"><a href="/things/1/">1</a></li>
        <li><a href="/things/2/">2</a></li>
        <li class="next"><a href="#"></a></li>
      </ol>
 </section>

Answer №1

The issue with the stacking of the ol elements is due to how you are handling the DOM traversal in your code. By assigning $postNav = $('ol.pagenation'), you are capturing a snapshot of the elements at that moment and storing them in the variable $postNav.

This means that any new ol.pagenation elements added later are not included in the initial collection stored in $postNav. To resolve this, you have two options:

  1. Remove existing ol.pagenation elements within the get_posts function by calling $('ol.pagenation').remove()
  2. Update the $postNav variable each time you add new ol.pagenation elements to the DOM by reassigning it like so: $postNav = $('ol.pagenation');. This ensures that $postNav always contains the latest elements.

The advantage of option 2 is that any other functions needing access to $postNav will always work with the most up-to-date DOM elements. If you do not require access elsewhere, option 1 may be sufficient.

JSFIDDLE OPTION 1

JSFIDDLE OPTION 2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you retrieve attributes from a specific element within a dropdown menu?

I came across this intriguing HTML code snippet: <select id="selectSomething"> <option id="4" data-name="tomato" data-email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfbba0a2aebba08fbbe1aca0a2">[email ...

In the matrix game, if a user chooses two balls of the same color, those two matching color patterns will be eliminated

I am currently working on a matrix game with the following condition: When a user selects two balls of the same color, they will destroy the two patterns with the same color. I have successfully implemented horizontal and vertical selection. However, I ...

Setting the default dropdown option in Angular

For my latest question, I decided to utilize ng-init. However, upon loading the page, I noticed that there is a blank default option. When I click and select another option, the blank option disappears. How can I remove this initial blank option? Here is ...

Concatenating strings with JavaScript

I am currently working on building a web page using a combination of html and javascript. I have a json file that provides inputs for some specific content I need to display. My main goal is to set up an address variable in order to show the Google Maps AP ...

There is nothing like Python Bottle when it comes to parsing JSON data from

In my React code, I have the following: const payload = { x : x, y : y } fetch("http://localhost:8080/update_game", { method: "POST", body: JSON.stringify(payload)}) And in Python, I have this implementation: @post(&ap ...

Is there a way to detect when the escape key is pressed?

Is there a way to detect when the escape key is pressed in Internet Explorer, Firefox, and Chrome? I have code that works in IE and alerts 27, but in Firefox it alerts 0 $('body').keypress(function(e){ alert(e.which); if(e.which == 27){ ...

Pressing a key once causing two actions when managing content in a separate window

Issue: I am facing a problem where I receive double keypresses from one key event when the event updates content in two separate windows. (Please keep in mind that I am not an expert in this field and appreciate your understanding.) I am attempting to use ...

Binding hover and load events using jQuery on elements that are dynamically generated

One should note that the click event can be successfully bound to an element with the class name keybox, even if this element is dynamically generated. The code for this would look like: $('body').on('click', '.keybox', funct ...

Having trouble getting the Facebook Like Box to function properly

I am having trouble displaying the like box on my website. I followed the code provided at https://developers.facebook.com/docs/plugins/like-box-for-pages and even tried using the HTML5 version, but nothing appears on the page. This is the code I used: & ...

Adjust the location of the slider scrollbar in jQuery UI

Currently, I am implementing jQuery UI's slider scrollbar and my goal is to set its position upon page load. Although I have referred to the sample code provided, my experience with jQuery UI is limited, so I am unsure about the necessary modification ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

A valid ReactComponent must be returned in order to properly render in React. Avoid returning undefined, an array, or any other invalid object

While working on my react application, I came across an error that I have been trying to troubleshoot without any success. It seems like I must be overlooking something important that could be quite obvious. *Error: VideoDetail.render(): A valid ReactComp ...

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...

Node.js Express application: Managing endpoint conflicts

After searching for a solution to this issue and not finding one, I apologize if this question is repetitive. In my express+node.js application, I have two endpoints defined as follows: // Retrieves a tweet by unique id app.get('/tweets:id', fu ...

Tips for displaying multiple results from a MySQL query in a single .ejs file using Node.js and Express

Currently diving into Node.js and working on a web application, I am faced with the challenge of rendering twice in the same .ejs file. Consider the scenario presented in the following .ejs file: <table> <% rows.forEach(function(ind){ %> /* m ...

Organize data that is deeply nested

Struggling to normalize deeply nested API response data? Look no further than https://github.com/paularmstrong/normalizr. This tool can help simplify your data structure. For example, if your input data looks like this: const data = [{ id: 'compone ...

Save the JWT token securely within a closure

Someone mentioned that the recommended way to store JWT tokens is as follows: access_token in the application memory (like closures) refresh_token in cookie entries (HttpOnly) Currently, my access_token is stored in localStorage and used for checking aut ...

Using jQuery and Ajax to populate a dropdown menu with options

I'm currently working on an ajax call function that successfully fills a drop-down list with data from a specific URL. However, I am looking to modify the function so that it can receive variables in order to populate the drop-down list dynamically. ...

My function seems to be functioning perfectly fine in Angular and Express, but for some reason, it's not working in Parse Cloud Code. What could

I am facing an issue with my code where it seems to be stuck. After testing it in both Angular and Express, I realized that the code is only progressing up to a certain point due to the requirement of the Master Key to edit the User table with new data. ...