`Why is insertAfter in jQuery not working?`

I am currently attempting to reposition the #whatsOnLink below the "Get a Quote" button throughout the website using jQuery. However, I am encountering some difficulties with the jQuery implementation. If I exclude the extra part of .button from the target selector, it works fine but I specifically need it to be placed within the containing div.

$('div[class^="grid"] a#whatsOnLink').each(
  function() {
    $(this).insertAfter($(this).closest("div[class^='grid_3'] div .button"));
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="grid_3 alpha omega selected cheapest">
  <div class="cheapest-body">

    <div class="cheapest-heading">
      <p>BEST VALUE</p>
    </div>

    <a id="whatsOnLink" href="">Test</a>

    <p class="latest-type">Silver apartment
      <br>from <span class="latest-offer-price">£75</span>  <span>pp</span>  <a class="lightbox lightbox-accomodation-more-info lightbox-added" href="/accommodation-overlays/bognor-regis-silver-apartment.aspx"><span>More Information</span></a>
    </p>

    <a class="button bookingEngine button-red" href="">
      <span>Get A Quote</span>
    </a>

    <img src="" class="grey-out-overlay">

  </div>
</div>

Your assistance is greatly appreciated.

Best regards, Kieran

Answer №1

Try using this code snippet:

$(this).closest('div[class^="grid_3"]').find('div .button')

Instead of:

$(this).closest('div[class^="grid_3"] div .button')

$(document).ready(function() {

  $('div[class^="grid"] a#whatsOnLink').each(
    function() {
      $(this).insertAfter($(this).closest('div[class^="grid_3"]').find('div .button'));
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="grid_3 alpha omega selected cheapest">
  <div class="cheapest-body">

    <div class="cheapest-heading">
      <p>BEST DEAL</p>
    </div>

    <a id="whatsOnLink" href="">Example Link</a>

    <p class="latest-type">Gold apartment
      <br>from <span class="latest-offer-price">$100</span>  <span>pp</span>  <a class="lightbox lightbox-accomodation-more-info lightbox-added" href="/accommodation-overlays/gold-apartment.aspx"><span>More Info</span></a>
    </p>

    <a class="button bookingEngine button-red" href="">
      <span>Book Now</span>
    </a>

    <img src="" class="overlay">

  </div>
</div>

Answer №2

To achieve this, you can utilize the .next() method

$('div[class^="grid"] a#whatsOnLink').each(function() {
  $(this).insertAfter($(this).next().next());

  // OR

  // $(this).appendTo($(this).parent());
});

$('div[class^="grid"] a#whatsOnLink').each(function() {
  $(this).insertAfter($(this).next().next());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid_3 alpha omega selected cheapest">
  <div class="cheapest-body">

    <div class="cheapest-heading">
      <p>BEST VALUE</p>
    </div>
    <a id="whatsOnLink" href="">Test</a>
    <p class="latest-type">Silver apartment
      <br>from <span class="latest-offer-price">£75</span>  <span>pp</span>  <a class="lightbox lightbox-accomodation-more-info lightbox-added" href="/accommodation-overlays/bognor-regis-silver-apartment.aspx"><span>More Information</span></a>
    </p>
    <a class="button bookingEngine button-red" href="">
      <span>Get A Quote</span>
    </a>
    <img src="" class="grey-out-overlay">
  </div>
</div>

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

What methods can I use to stop the styles of a child component from impacting those of the parent component

Is there a way to create CSS rules that achieve the following conditions? The parent component's CSS does not impact the child component The child component's CSS does not affect the parent component The child component is sourced from an exte ...

Avoid selecting the hidden element using the :first-child pseudo-class

I've encountered an issue while using Sortable.js. The problem is as follows: I have a list of items that need to be sorted, with the first element wider than the rest. To achieve this, I've applied the following CSS: #produto_img { display: ...

Using ng-repeat in Angular causes the style of a div to become hidden

Utilizing angular ng-repeat to generate multiple divs, the original template html code is as follows: <div class="span5 noMarginLeft"> <div class="dark"> <h1>Timeline</h1> <div class="timeline"> <div c ...

Why Electron is refusing to open a JSON file

Currently, I am attempting to populate filenames using JSON for the onclick='shell.openItem('filename') function. While the console.log(data[i].url) correctly displays the kmz files for each button, I encounter an error when clicking a butto ...

Visualizing data with a grouped bar chart in D3.js

I am currently working on creating a vertical bar chart using D3.js, similar to the one shown in this https://i.sstatic.net/pig0g.gif (source: statcan.gc.ca) However, I am facing an issue as I am unable to display two sets of data for comparison. Follow ...

Is there an issue with invoking Spring controller methods from JavaScript (via ajax) that is causing them

Using JavaScript to send a request to a method in Spring controller, the code looks like this: <script language="javascript" type="text/javascript"> var xmlHttp function show() { if(typeof XMLHttpReques ...

Mastering the art of manipulating arrays with jquery

Trying to implement a dynamic search bar feature using jQuery. Here is the code snippet: Fiddle : https://jsfiddle.net/fpLf1to4/ var inputSearch = $('.searchInput').hide(); var searchArray = ['s','e','a',& ...

Data is not returned following an echoed Ajax call

The issue I am currently facing is that the ajax call is successfully updating the record but it is not returning the string of echo as expected. This script was previously functioning without any problems, however, after some sort of upgrade, it seems to ...

Trouble with escaping characters in Javascript?

My code looks like this: `message.channel.send( const Discord = require('discord.js'); const client = new Discord.Client(); const token = 'your bot token here'; client.on('ready', () => { console.log('I am ready!& ...

The function to set the state in React is malfunctioning

I'm currently in the process of developing a website where I utilize fetch to retrieve information and display it to the user. Initially, I opted to save this data in a state variable, but for some reason, it's not functioning as expected. Upon ...

What is the use of static width in col-xl-* (Bootstrap 4)?

Is there a way to prevent my col-xl-* from growing too large on larger monitors? I've noticed that when I view it on my laptop (1280 width) and desktop (1920), the col-xl setting is either too big on the desktop or too small on the laptop. <div c ...

Tips for executing several JavaScript files using the Node.js command line?

I am looking to launch 4 scripts using Node.js. myapp -script1.js -script2.js -script3.js -app.js -package.json .... .... I attempted to run them with the following commands: node script1.js && node script2.js && node scrip ...

Using Swift to seamlessly highlight text during a Javascript search

I've created a text-searching feature similar to ⌘ + F for an iOS app, and it's functioning well. However, I'm facing two issues: When someone searches in Arabic, the words become disconnected. Users can't search if there are di ...

What are your preferred HTMLPurifier configurations for sanitizing CSS styles?

I'm currently in the process of developing an application that allows users to input their own custom CSS for their profiles, similar to platforms like MySpace, Friendster, and Blogger. However, I'm struggling to find an effective method to prot ...

Is it possible to encase the callback function of an asynchronous xmlhttprequest within another function?

I am using asynchronous XMLHttpRequests to fetch data from an API in pure JavaScript for the chrome extension I am developing. Here is the code snippet: function getInfo(url, callback) { var xmlhttp; xmlhttp = new XMLHttpRequest(); xmlhttp.onr ...

The utilization of local storage within Backgridjs

I am creating an app using Backbone.js (Marionette Framework) along with additional functionalities like Backgrid, Backbone local storage, Backbone Radio, epoxy, and Backbone relational model. Encountered Problem: An issue arises when utilizing the local ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

Is it possible to determine the success or failure of an asynchronous function when the function itself already handles errors?

The architecture of my app is currently set up with functions that are scoped to specific modules, such as "Auth" for instance: async function authenticate(email) { let authenticated = false; try { if (email) { if (!validEmail(email) ...

React input field keeps losing focus during re-render operations

My current project involves using React to create an input text that displays a value from an in-memory data store and updates the store when the input value changes, triggering a re-render. However, I am facing an issue where the input text loses focus du ...

Pass the specific index of an object located outside of a v-for loop in Vue 3

For educational purposes, I am working on building a basic shopping cart using Vue 3. So far, I have successfully set up the products object and implemented the addToCart() functionality. Everything is functioning smoothly within a v-for loop. However, t ...