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

Tips for stopping execution in Discord.js if the user no longer exists?

I'm currently working on a discord bot and encountered a minor issue. I am using "messageReactionRemove" and "messageReactionAdd" to manage certain roles by removing or adding them, but the problem arises when a user leaves the server. When this happe ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...

Exploring the Differences Between NPM Jquery on the Client Side and Server

I'm still getting the hang of node and npm, so this question is more theoretical in nature. Recently, I decided to incorporate jQuery into my website by running npm install jquery, which placed a node_modules directory in my webpage's root along ...

Adding a delay between calls to the addClass() function in jQuery

Having trouble setting my delay as described in this post: jQuery: Can I call delay() between addClass() and such? Unfortunately, it's not working for me. JSFiddle $( "#nav2" ).click(function() { var notshown = $("#dropdown1", "#dropdown2"); ...

jQuery not functioning properly when attempting to add values from two input boxes within multiple input fields

I am facing an issue with a form on my website that contains input fields as shown below. I am trying to add two input boxes to calculate the values of the third input box, but it is only working correctly for the first set and not for the rest. How can ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

Android not showing scroll bar in ion-scroll feature

I am experiencing an issue where a div with a fixed height displays a scroll bar on browsers but not on an Android phone. <ion-scroll style="height:300px;" scrollbar-y='true'> //content </ion-scroll> ...

What is the best way to initiate a collapsed jQuery toggle?

Is there a way to make a jQuery toggle collapsed by default? I've looked at some examples, but none of them seemed to fit my specific setup and I couldn't quite figure them out. Here's the HTML code: <table border="0" width="100%" alig ...

Drag Bootstrap panels to the edge of the column

I need to position two panels in a column, with one on the left and the other on the right. Currently, they are not aligned properly, as shown in this image: https://i.stack.imgur.com/RU636.png The first panel should be moved to the left to align with the ...

Why is it necessary to decode JSON stringified objects in Vue props?

When passing a stringifyed object via props to a component, it seems like there is an issue with the data transformation. <my-component :filter="stringobject" ></my-component> stringobject = "{"search_text":"(ciCl ...

Is it possible to utilize a variable as a selector for the nth element?

Is there a way to select all elements with the class .formRow that have a value greater than a specified variable (x)? How can I reference this variable within the tag? $(document).ready(function(){ var x = 1; $('.formRow:nth('x') ~ .fo ...

Possible solution to address the issue: xhr.js:178 encountered a 403 error when attempting to access https://www.googleapis.com/youtube/v3/search?q=Tesla

Encountering this console error: xhr.js:178 GET https://www.googleapis.com/youtube/v3/search?q=river 403 A specific component was designed to utilize the API at a later point: const KEY = "mykeyas23d2sdffa12sasd12dfasdfasdfasdf"; export default ...

Tips for showing only the date (excluding time) from a get operation in javascript (specifically using node js and mysql)

I recently built a CRUD application using Node.js and MySQL. However, I am facing an issue where I am unable to display the date without the time and in the correct format. { "id": 1, "name": "Rick Sanchez", "dob": & ...

Remove Request (MongoDB, express, handlebars)

Struggling with implementing a delete request in my application. I have a database filled with reviews that I manipulate through my app. Currently, I'm attempting to create a function that will remove a document from the database and then redirect th ...

Firefox fails to apply styling to content loaded through Ajax (particularly when using AngularJS)

I've encountered a strange problem while working on my app (MVC4 + AngularJS). It seems that in Firefox (currently version 42), content loaded through an Ajax call does not always pick up the CSS styles that were loaded before. In the attached images, ...

The div is incorrect and causing the label and input to move in the wrong direction

Whenever I try to adjust the position of the current-grade-name-input, the entire grade-point-input moves along with it inexplicably. /* final grade calculator: (wanted-grade - (current-grade * (1 - final%))) / final% Ex: have a 80 an ...

Problem with stellar.js, boostrapv4, and jQuery 3.2.1 (lack of jQuery migrate support)

Having some issues integrating stellar with Bootstrap v4 and jQuery 3.2.1 as I keep encountering the error message "Uncaught TypeError: elem.getClientRects is not a function" Check out this JSFiddle link $.stellar({ horizontalScrolling: false, vertic ...

Is it possible to extract the CSS path of a web element using Selenium and Python?

I am working with a collection of elements using find_elements_by_css_selector, and my next task is to extract their css locators. I attempted the following approach: foo.get_property('css_selector') However, it seems to be returning None. ...

A guide to integrating ffmpeg with NuxtJS

I am completely new to Nuxt and currently in the process of migrating a Vue application that generates gifs using ffmpeg.wasm over to Nuxt.js. However, every time I try to access the page, the server crashes with the following error message: [fferr] reques ...

Querying data from a promise and embedding it in a JSON object in AngularJS

Attempting to retrieve data from a promise within a JSON object for the first time has presented me with a challenging task. The typical approach looks something like this: Service JS app.factory("dataService", ["$http", function ($http) { fu ...