Enhance the appearance of 6 image URLs by wrapping them in dynamic divs with the

Can someone assist me in displaying 6 images retrieved from a MySQL database on an MVC Razor view? Images 1 and 6 should be placed in separate divs labeled "item", while images 2, 3, 4, and 5 should be grouped together in a div called "item-small". Below is the current rendering:

<div class="owl-photos">

    <a href="post.html" class="item-photo">
      <img src="images/photos/image-1.jpg" alt="" />image1
    </a>

    <a href="post.html" class="item-photo">
      <img src="images/photos/image-2.jpg" alt="" />image2
    </a>

    <a href="post.html" class="item-photo">
      <img src="images/photos/image-3.jpg" alt="" />image3
    </a>
    <a href="post.html" class="item-photo">
      <img src="images/photos/image-4.jpg" alt="" />image4
    </a>
    <a href="post.html" class="item-photo">
      <img src="images/photos/image-5.jpg" alt="" />image5
    </a>

    <a href="post.html" class="item-photo">
      <img src="images/photos/image-6.jpg" alt="" />image6
    </a>

  </div>

Here is what I am aiming for:

<div class ="owl-photos">

<div class="item">  
<a href="post.html" class="item-photo">
<img src="images/photos/image-1.jpg" alt="" />image1
</a>
</div>


<div class="item item-small">
<a href="post.html" class="item-photo">
<img src="images/photos/image-2.jpg" alt="" />image2
</a>
<a href="post.html" class="item-photo">
<img src="images/photos/image-3.jpg" alt="" />image3
</a>
<a href="post.html" class="item-photo">
<img src="images/photos/image-4.jpg" alt="" />image4
</a>
<a href="post.html" class="item-photo">
<img src="images/photos/image-5.jpg" alt="" />image5
</a>
</div>


<div class="item">
<a href="post.html" class="item-photo">
<img src="images/photos/image-6.jpg" alt="" />image6
</a>
</div>
</div>

I would appreciate any assistance in using jQuery to achieve this. I am having trouble finding a starting point. Adding classes to the first element seems particularly challenging.

I have attempted the following code:

$(".owl-photos>div:nth-child(1n)").before("<div class="item">");
$(".owl-photos>div:nth-child(1n)").after("</div><div class="item item-small">");
$(".owl-photos>div:nth-child(1n)").after("<div class="item item-small">");
$(".owl-photos>div:nth-child(5n)").after("</div><div class="item ">");
$(".owl-photos>div:nth-child(6n)").after("</div>");

Answer №1

$(function () {
  var $result = $('<div class="owl-photos"></div>');

  var length = $('.owl-photos a').length;

    $('.owl-photos a').each(function (key, item) {
    if (key == 0 || key == length - 1) {
      var $div = $('<div class="item"></div>').append(item);
      $result.append($div);
    } else {
      var $small = $result.find('.item-small');
      console.log($small);
      if (!$small.length) {
        var $div = $('<div class="item item-small"></div>').append(item);
        $result.append($div);
      } else {
        $small.append(item);
      }
    }
  });

  $('.owl-photos').html($result.html());
});

https://jsfiddle.net/atw4gwrr/

Answer №2

If you want to dynamically create elements using JavaScript, you can do so by appending specific elements and then inserting the newly created elements into the .owl-photos container. When you append the <a> elements to the new <div> containers, they are effectively moved from their original location, preventing any duplication.

In the example below, I first retrieve the list of child elements and group them as follows:

  • The first child is wrapped in a <div class="item"> container and appended.
  • The elements that are not the first or last child are wrapped in a
    <div class="item item-small">
    container and appended.
  • The last child is wrapped in a <div class="item"> container and appended.

$(function(){
  var $photos = $('.owl-photos'),
      $childs = $photos.children(),
      $itemWrapper = $(document.createElement('div')).attr('class','item'),
      $itemSmallWrapper = $(document.createElement('div')).attr('class','item item-small');
  $photos.append(
    $itemWrapper.clone().append($childs.first()),
    $itemSmallWrapper.clone().append($childs.filter(':not(:first-child), :not(:last-child)')),
    $itemWrapper.clone().append($childs.last())
  );
})
.item { border: 3px solid green }
.item.item-small { border: 3px solid blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="owl-photos">
    <a href="post.html" class="item-photo">
      <img src="http://placehold.it/100x100&text=1" alt="" />image1
    </a>
    <a href="post.html" class="item-photo">
      <img src="http://placehold.it/100x100&text=2" alt="" />image2
    </a>
    <a href="post.html" class="item-photo">
      <img src="http://placehold.it/100x100&text=3" alt="" />image3
    </a>
    <a href="post.html" class="item-photo">
      <img src="http://placehold.it/100x100&text=4" alt="" />image4
    </a>
    <a href="post.html" class="item-photo">
      <img src="http://placehold.it/100x100&text=5" alt="" />image5
    </a>
    <a href="post.html" class="item-photo">
      <img src="http://placehold.it/100x100&text=6" alt="" />image6
    </a>
  </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

FireFox appears to be experiencing issues with accessing the contentDocument of a frame using jQuery

While this line of code functions correctly on Chrome and IE, it encounters an issue on FireFox. The error message displayed in the FireFox console is: ReferenceError: $ is not defined var lang = $($('#navFrame')[0].contentDocument).find('# ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

Update the content of the widget

Currently, I am utilizing the following script to display NBA standings: <script type="text/javascript" src="https://widgets.sports-reference.com/wg.fcgi?script=bbr_standings&amp;params=bbr_standings_conf:E,bbr_standings_css:1&amp"></sc ...

Using customized CSS code may not always be compatible with Bootstrap 5

One scenario I encountered was my attempt to change the background color of the body using style.css, but unfortunately, the code wasn't effective. Below is my reference to Bootstrap 5 and custom CSS: <link href="https://cdn.jsdelivr.net/npm/& ...

Tips for resizing images to fit within a TD cell in an HTML table

Currently, I have an issue with the image display within a TD element. Despite setting a specific width for the TD, the image appears to be wider than intended. Could you offer a solution to this problem? ...

No matter what I try, the design of my dialog box remains stubbornly unchanged

I am attempting to increase the width of my dialog box while also adding horizontal middle borders. It seems that my bootstrap for the site does not include these elements. How can I rectify this issue? Here is my code: $(document).ready(function() { ...

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

Error occurs when page rendering is stuck in a recursive loop: Excessive re-renders detected

My webpage contains several form components as listed below. While everything on the front end seems to be working fine, I noticed that the Fetchmovies function is being called repeatedly and an error is thrown in the console: caught Error: Too many re-ren ...

Tips for restricting camera movement in threejs

Being new to working with threejs, I am struggling to set limits on the camera position within my scene. When using OrbitControls, I noticed that there are no restrictions on how far I can zoom in or out, which I would like to change. Ideally, I want the c ...

Vue3 is struggling to apply dynamic styling exclusively to certain buttons

Currently, I am diving into the world of vue and facing a challenge in styling buttons dynamically when clicked individually. These buttons serve as filters for a list of products, and my goal is to apply one style when the filter is 'on' and ano ...

Troubleshooting jQuery.ajax - Why won't it function properly?

I've been struggling to get the ajax service functioning properly. I tried a simple $.get("http://google.com"), but it didn't work. Additionally, this code snippet failed as well: <html> <head> <script src="https://aja ...

ES6 import of CSS file results in string output instead of object

Too long; Didn't read I'm facing an issue where the css file I import into a typescript module resolves to a string instead of an object. Can someone help me understand why this is happening? For Instance // preview.ts import test from './ ...

Why do my tablet media queries take precedence over mobile view media queries?

I've noticed that when I view my website on mobile devices, the tablet media queries always seem to override my mobile media queries. Can anyone explain why this is happening? Here is how I have set it up: /* X-Small devices (portrait phones, less t ...

While utilizing a dynamic PHP navigation header, the nested divs are shifting below the container div

After successfully implementing a dynamic PHP header on my site, I encountered issues when trying to incorporate the remaining content within the container div along with the header div. The additional content is not displaying inside the container but is ...

Tips for sending a PHP array to jQuery AJAX using the $.post method

Goal: I am working with a php array variable and I want to pass this array ($key and $value) through jQuery AJAX using $.post to another php page called next.php. PHP Array Variable: $issue['key01']='value01'; $issue['key02 ...

Vue component updating its model only upon input element losing focus

I'm a beginner with vue and I'm currently working on incorporating an ajax search feature that triggers when a keyup event occurs. I have noticed that the model only updates when the input element loses focus. Sample HTML Code: <input name=" ...

Passing props from pages to components in NextJS: A guide

My nextjs-application has a unique folder structure: components -- layouts --- header.tsx --- index.tsx pages -- index.tsx -- [slug].tsx In the [slug].tsx file, I utilize graphql to fetch data and set the props accordingly: export default ...

What is the best way to manage a promise in Jest?

I am encountering an issue at this particular section of my code. The error message reads: Received promise resolved instead of rejected. I'm uncertain about how to address this problem, could someone provide assistance? it("should not create a m ...

Combine a variable and a string to create a new variable

@color-purple: "#ffffff" @colors: purple, light-purple, green, light-green, red, light-red, grey, light-grey, lightest-grey; .ColorsMixin(@i:0) when(@i =< length(@colors)){ //loop over icons array @color: extract(@colors, @i); //extract the ic ...

What is the best way to incorporate a custom modal created with HTML/CSS into my Bootstrap website?

I am facing an issue with the modal implementation on my bootstrap website. The modal is supposed to open when a user clicks a button. Strangely, it was working perfectly fine on another HTML/CSS file, but once I added it to this Bootstrap file, it stopped ...