Utilize jQuery to locate and add items that match specific data attributes to corresponding ID elements

In my HTML code, I have a group of spans within a div that I am attempting to match and relocate to a corresponding id. Each span contains a data attribute that corresponds to the parent ID of the target element. My goal is to utilize jQuery to find the matching data attributes in the spans and then insert them before a separate span within the parent div IDs.

Here is an excerpt from my code:

HTML

<div id="id-expand-2">
  <a class="thing" href="#">
    <div class="item-title">
      <span>Title 1</span>
    </div>
  </a>
</div>
<div id="id-expand-4">
  <a class="thing" href="#">
    <div class="item-title">
      <span>Title 2</span>
    </div>
  </a>
</div>
<div id="id-expand-6">
  <a class="thing" href="#">
    <div class="item-title">
      <span>Title 3</span>
    </div>
  </a>
</div>

<div class="vid-imgs">
  <span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
  <span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
  <span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
</div>

Essentially, I want each span within the vid-imgs class with the data-item attribute to align with the ID of its parent div and be inserted using .append() right after the item-title class.

The expected outcome would resemble:

<div id="id-expand-2">
  <a class="thing" href="#">
    <div class="item-title">
<span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
      <span>Title 1</span>
    </div>
  </a>
</div>
<div id="id-expand-4">
  <a class="thing" href="#">
    <div class="item-title">
<span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
      <span>Title 2</span>
    </div>
  </a>
</div>
<div id="id-expand-6">
  <a class="thing" href="#">
    <div class="item-title">
 <span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
      <span>Title 3</span>
    </div>
  </a>
</div>

I am uncertain about how to properly match each element altogether.

I was contemplating utilizing an each function like this:

$(".vid-imgs").each(function () {
  var items = $(".item").attr("data-item");
  console.log(items);
});

However, it appears to only retrieve the first item within the vid-imgs div. After staring at this for hours, I think my eyes need a break!

Answer №1

Just a few pointers:

  • To get the value of the data-item attribute of each .item, you should use

    $(".item").attr("data-item");
    . If you want to select a specific item by its id, consider using the CSS id selector.

  • Remember to loop through the span elements inside .vid-imgs, not just the container itself.

$(".vid-imgs span").each(function () {
  var items = $("div#"+$(this).data('item'));
  items.append(this.cloneNode(true));
  this.remove(); //remove the span
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id-expand-2">
  <a class="thing" href="#">
    <div class="item-title">
      <span>Title 1</span>
    </div>
  </a>
</div>
<div id="id-expand-4">
  <a class="thing" href="#">
    <div class="item-title">
      <span>Title 2</span>
    </div>
  </a>
</div>
<div id="id-expand-6">
  <a class="thing" href="#">
    <div class="item-title">
      <span>Title 3</span>
    </div>
  </a>
</div>

<div class="vid-imgs">
  <span class="item" data-item="id-expand-2"><img src="https://www.fillmurray.com/g/140/100" /></span>
  <span class="item" data-item="id-expand-4"><img src="https://www.fillmurray.com/g/140/100" /></span>
  <span class="item" data-item="id-expand-6"><img src="https://www.fillmurray.com/g/140/100" /></span>
</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 is the concept of nested includes in sequelize?

Is it possible to perform a nested include in Sequelize? I have a table called products that has a one-to-many relationship with comments, and the comments table has a many-to-one relationship with the users table. Each comment has a user_id and product_id ...

Having some trouble getting Backstretch to function properly. It keeps giving me a 404 error when I attempt to load it

In my free time, I am working on a small webpage using python/django with bootstrap. Frontend development is not my strong suit, so I try to keep things simple. Recently, I came across the backstretch plugin and thought it would be easy to set up and add a ...

Unable to alter the protocol option of the request object in SailsJS

Currently, I am utilizing a library that relies on the req.secure option to proceed without any errors. However, my application is deployed on Heroku and I have implemented custom middleware to check the "x-forwarded-proto" header and set req.secure as tru ...

In-depth preg_match_all analysis

I'm encountering an issue with my detailed preg_match_all not working as expected. Instead of retrieving the desired data, I am getting a blank Array. Below is the code snippet I'm struggling with: <?php $remote_search = file_get_content ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

Automatically execute a function when the number input changes, but only if no further changes are detected after a certain period of time

I am implementing angularjs with an input field for numbers. I want to trigger an action automatically after a certain amount of time, but only if no further changes have been made to the number within that time frame (let's say 2 seconds). In my exa ...

Error in TypeScript: The property 'data' is not found within type '{ children?: ReactNode; }'. (ts2339)

Question I am currently working on a project using BlitzJS. While fetching some data, I encountered a Typescript issue that says: Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339) import { BlitzPage } from &q ...

Animating jQuery Accordion in Horizontal Direction Extending to the Far Right

After implementing a horizontal accordion in jQuery based on the tutorial found at the following link: A minor issue arose during animation where a slight space was added on the far right side, causing the tabs to shift slightly. This problem is particula ...

Is there a way to convert inline styling to CSS using Material-ui within a React component?

In my development work with React, I initially utilized inline styling to customize the appearance of material-UI components. However, I have come to realize that utilizing CSS provides a more structured and efficient approach to styling components. Despit ...

Calculating the total of time values using Javascript

I am working with a set of time values stored as JSON data: 14:49:09 00:16:46 00:00:05 My goal is to loop through these times and calculate their sum to obtain the final total time: The resulting time will be 15:06:00 using Javascript. ...

Ways to avoid triggering document.ajaxstart on a particular selector

I have the following jQuery call on a textbox. I need to disable ajaxStart() for this specific selector. $("#ddl_select").keyup(function() { var searchid = $(this).val(); var dataString = 'search='+ searchid; if(searchid!='&ap ...

`Why is it important to debug javascript code?`

I have some outdated JavaScript code that surprisingly still works in Internet Explorer from 2000-2002, but refuses to function properly in browsers like Firefox, Chrome, and Opera. I've come across various browser quirks where different browsers inte ...

The D3 path is generating an unexpected output of 0px by 0px, causing the map not to display properly. I am currently unsure how to adjust the projection to

I am currently working on creating a world map using D3. I obtained the JSON file from the following link: https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json Below is the code snippet I'm using: // Defining SVG dimensio ...

The date-fns parse function will retrieve the value from the previous day

When attempting to parse a date using the date-fns library, I am encountering an issue where the resulting date is one day prior. How can this be resolved in order to obtain the correct result? start = '2021-08-16' const parseStart = parse(start, ...

Tips for finding information within a table using HTML

My task involves creating a table with the option for users to search data within it. However, I have encountered an issue where I am only able to search for data in the first row of the table. <table style="width:100%" id="table"> <tr> ...

What steps should I follow to make a dynamic carousel card with Bootstrap that adjusts to different screen sizes

My goal was to design a Bootstrap card with an embedded 'slideshow'. The idea was to use the second page to provide more information about the content on the first page. While editing this on the web, I managed to create a satisfactory product () ...

Reviewing and Implementing React and Material-UI Autocomplete for Selecting Multiple

Having trouble using Formik and MUI Autocomplete with multiple items. Specifically, when searching for "Pencil", it doesn't highlight the item. Also, you can select it twice by clicking on it. Desired outcome: Being able to select one or more items. ...

Designing a flexible layout that allows for both vertical and horizontal scrolling of content

I have successfully implemented a flexbox layout with fixed header, fixed footer, fixed menu, and scrolling content based on resources from various articles and Stack Overflow answers. However, I am facing difficulty in achieving horizontal scrolling for ...

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...

Issue with Django where only one out of six buttons is assigned the jquery popup window

Currently developing a cookbook website and facing a challenge. Attempting to integrate django pagination with a sleek popup jquery plugin found at this link: Encountering an issue where only the first recipe button activates the popup window, displaying ...