Tips for generating numerous sub div tags using jQuery

Is there a way to achieve this output with jQuery? I have working code here: . (See image for reference: https://i.stack.imgur.com/eOXiN.png)

When trying to replicate the same using jQuery, I encountered an issue where there is no spacing between two images and no "add wish" button displayed at the bottom.

Here is my attempt:

For visual representation, here is the corresponding image: https://i.stack.imgur.com/PKu6o.png

Answer №1

simply update your script

  $.each(numbers, function () {
                $(".product-loop").append("<div class='col-sm-4' id='col" +numbers[num] + "'></div>")
                $("#col" + numbers[num]).append($("<div class='product-image-wrapper' id='img-wrap" + numbers[num] + "'></div>"))
                $("#img-wrap" + numbers[num]).append($("<div class='single-products' id='singlePro" + numbers[num] + "'></div>"))
                $("#singlePro" + numbers[num]).append($("<div class='productinfo text-center' id='productCentre" + numbers[num] + "'></div>"))
                $("#productCentre" +numbers[num] ).append($("<img src='http://www.tutorialspoint.com/images/html.gif' alt=''/>\
                                              <h2>$52</h2>\
                                              <p>Easy Polo Black Edition</p>\
                                               <a href='#' class='btn btn-default add-to-cart'>\
                                               <i class='fa fa-shopping-cart'></i>Add to cart</a>"))
                $("#singlePro"+numbers[num] ).append($("<div class='product-overlay' id='productOverlay"+numbers[num] +"'></div>"))
                $("#productOverlay"+numbers[num] ).append($("<div class='overlay-content' id='overlayContent" + numbers[num] + "'></div>"))
                $("#overlayContent"+numbers[num] ).append($("<h2>$66</h2><p>Easy Polo Black Edition</p><a href='#' class='btn btn-default add-to-cart'><i class='fa fa-shopping-cart'></i>Add to cart</a>"))

                $("#img-wrap" + numbers[num]).append($("<div class='choose' id='chse"+ numbers[num]+"'></div>"))
                $("#chse"+numbers[num] ).append($("<ul class='nav nav-pills nav-justified'>\
                                            <li><a href=''><i class='fa fa-plus-square'></i>Add to wishlist</a></li>\
                                                <li><a href=''><i class='fa fa-plus-square'></i>Add to compare</a></li>\
                                        </ul>\
                                        "))
                num += 1;
            });
        });

Demo :

Answer №2

There appears to be some issues happening here, as IDs are meant to be unique so having 6 '#productCentres' is not ideal.

I believe they were supposed to be within the 'product-loop' container which you overlooked using;

insertAfter(".product-loop")

It seems like;

$(".product-loop div:eq(0)")

was meant to attach the cart option buttons to each product, but since insertAfter placed them outside, it never matched the selector.

To make things clearer and easier for modification, I refactored the complex .each call into a function so each element can be built individually and styled/modified as needed.

I didn't include the CSS due to character limitations, but adding padding to '.productCentre' will help create the missing gutters in your design.

function newProduct(id) {
    product = document.createElement("div");
    product.setAttribute('class', 'productCentre col-sm-4 product-image-wrapper single-products productinfo text-center');
    product.setAttribute('id', id);
    
    // Rest of the code follows...
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<section>
  <div class="container">
    <div class="row">
      <div class="col-sm-9 padding-right">
        <div class="features_items">
          <!--features_items-->
          <h2 class="title text-center">Features Items</h2>
          <div class="product-loop">

          </div>
        </div>
        <!--features_items-->
      </div>
    </div>
  </div>
</section>

Answer №3

Just like @Evil Saied, there are some issues in your code that need to be addressed. The major concern is the presence of duplicate ids.

It appears that you may have mistakenly added classes to the incorrect element (e.g., .product-image-wrapper).

The underlying problem

$("#col").append($("<div></div>")).addClass("product-image-wrapper").attr("id","img-wrap")

You can see that the class product-image-wrapper was added to #col, but not to the newly created div.

The solution

$("#col").append($("<div></div>").addClass("product-image-wrapper").attr("id","img-wrap"));

In essence, you need to move the closing parentheses ) to the end.

I removed irrelevant parts of the CSS to create a snippet. In the future, please provide only the pertinent code for easier troubleshooting.

$(function(){
  var numbers = [1,2,3,4,5,6];
  $.each(numbers,function(){
    $("<div></div>").addClass("col-sm-4").attr("id","col").insertAfter(".product-loop");
    $("#col").append($("<div></div>").addClass("product-image-wrapper").attr("id","img-wrap"));
    $("#img-wrap").append($("<div></div>").addClass("single-products").attr("id","singlePro"));
    $("#singlePro").append($("<div></div>").addClass("productinfo text-center").attr("id","productCentre"));
    $("#productCentre").append('<img src="http://www.tutorialspoint.com/images/html.gif" alt="" />\
<h2>$52</h2>\
<p>Easy Polo Black Edition</p>\
<a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>')

    $(".product-loop div:eq(0)").after("<div></div>").addClass("choose").attr("id","chse");
    $("#chse").append('<ul class="nav nav-pills nav-justified">\
<li><a href=""><i class="fa fa-plus-square"></i>Add to wishlist</a></li>\
<li><a href=""><i class="fa fa-plus-square"></i>Add to compare</a></li>\
</ul>');
  });
});
@import url(http://fonts.googleapis.com/css?family=Roboto:400,300,400italic,500,700,100);
@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,800,300,600,700);
@import url(http://fonts.googleapis.com/css?family=Abel);

.product-image-wrapper {
  border: 1px solid #F7F7F5;
  overflow: hidden;
  margin-bottom: 30px;
}

body {
  font-family: 'Roboto', sans-serif;
  background:;
  position: relative;
  font-weight:400px;
}

ul li {
  list-style: none;
}

a:hover {
  outline: none;
  text-decoration:none;
}

a:focus {
  outline:none;
  outline-offset: 0;
}

a {
  -webkit-transition: 300ms;
  -moz-transition: 300ms;
  -o-transition: 300ms;
  transition: 300ms;
}

h1, h2, h3, h4, h5, h6 {
  font-family: 'Roboto', sans-serif;
}

.btn:hover, 
.btn:focus{
  outline: none;
  box-shadow: none;
}

.navbar-toggle {
  background-color: #000;
}

a#scrollUp {
  bottom: 0px;
  right: 10px;
  padding: 5px 10px;
  background: #FE980F;
  color: #FFF;
  -webkit-animation: bounce 2s ease infinite;
  animation: bounce 2s ease infinite;
}

a#scrollUp i{
  font-size: 30px;
}
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<section>
  <div class="container">
    <div class="row">
      <div class="col-sm-9 padding-right">
        <div class="features_items">
          <!--features_items-->
          <h2 class="title text-center">Features Items</h2>
          <div class="product-loop">
          </div>
        </div>
        <!--features_items-->
      </div>
    </div>
  </div>
</section>

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

Creating a dynamic cascading dropdown list with Vue.js: Step-by-step guide

I successfully implemented a dropdown list using Vue.js, but now I want to add another similar list. How can I set this up? Here are the codes for both dropdown lists: var addUserVue = new Vue({ el: "#app", data: { heading: "Vue Select Cas ...

Are you experiencing issues with your Ajax request?

I've been struggling to retrieve json data from an API. Despite my efforts, the GET request seems to be executing successfully and returning the correct data when I check the Net tab in Firebug. Can anyone offer advice on what could be going wrong or ...

Exploring the distinctions among different xpath implementations in Selenium WebDriver

Looking at this snippet of HTML code: <div id="divTooltips_Section_Filter" style="float:right; padding-right: 30px; padding-bottom: 10px;"> <img src="/mkteditor/css/images/tooltip.png" width="25px" height="25px" alt=""> </div> I've ...

Struggling with my Transform Origin in CSS for SVG

I have two classes (firstCircle & spin) on the first circle on the left, and I'm attempting to make it rotate in place. After removing them from the css so you can see the circle, I am having trouble with transform-origin. My code seems wrong as i ...

When I incorporate JavaScript logic into my navigation, the Anchor Links fail to work properly

Currently facing an issue with my navigation bar where the category jump labels should change their bootstrap class when the corresponding heading is visible in the viewport. While everything works fine up to this point, adding the second event listener fo ...

Can I kindly request assistance with implementing jQuery Autocomplete on a C# IHttpHandler in a non-sequential

Currently, I have an autocomplete textbox that is requesting an IHttphandler through IIS7 using C#. However, it seems like the requests reaching the web server are arriving unordered. Below is a snippet of the log obtained from the IHttpHandler after typ ...

Using Laravel to Transfer Information to a Controller through AJAX without a Form

I am facing an issue with sending data via JS to a Laravel controller on button click. I cannot use a form as the data is being generated dynamically. When attempting to send the data, I keep receiving an Internal Server Error (500), but I am unable to cat ...

Shuffle the elements within each container in the DOM

Currently, I am focusing on designing a card-based layout where each card contains details about the product. One important detail is the phone number, which is displayed in the format 555-555-5555. My current goal is to clear the text value of the phone ...

Switch up the stylesheet in WordPress when an administrator is signed in

Looking for a way to incorporate conditional PHP code into my theme that will load a different stylesheet when either an admin or a specific user (ID=1) is logged in. Does WordPress have a function that can make this happen? There's a particular div ...

Handling AJAX requests using jQuery

I'm currently in the process of learning how to utilize jQuery Ajax. Could you explain to me the significance of function(response), as well as what exactly is meant by response == 1 and response == 2? jQuery.post(ajaxurl, data, function(response) { ...

Listening for an event or using a CSS pseudo-class to detect when the scrollbar becomes

Are there any JavaScript event listeners or CSS pseudo classes that can detect when a scrollbar appears and disappears? For example, on Mac OS and Windows Internet Explorer 10 or newer, the scrollbars are hidden by default but appear when scrolling begins. ...

What is the syntax for implementing conditional statements within the style jsx of Next.js?

Recently, I've been exploring the use of <style jsx> in my Next.js project and encountered a scenario where I needed to style an element based on a conditional statement. Additionally, my project relies on tailwindCSS for styling: <div classN ...

Updating a CSS file through jQuery is proving to be ineffective

After searching extensively on Stack Overflow and other websites, I have not been able to find a clear answer to my question regarding changing a CSS class (#navbar a) after a specific function is triggered. My understanding of jQuery and JavaScript is lim ...

Resizing popups upon button activation

Hey there! I have a popup with a button that reveals random text containing between 0 to 32 words when clicked. The issue is, the popup keeps resizing based on the length of the text, causing the button to move around. Is there a way I can keep the button ...

Designing a fresh look for the developer portal on Azure API Management Services

Is there a way to customize the color of the navbar links in the fresh developer portal for different layouts? I have attempted using the designer tool provided by the portal, but it hasn't yielded any results. I also tried cloning the git repository ...

Enhance your Magento store with a personalized layout update

Is there a way to call a stylesheet from my skin folder instead of pointing to my base path? Right now I have <reference name="head"> <action method="addCss"> <stylesheet>yourtheme/css/red.css</stylesheet> < ...

The -webkit-linear-gradient effect can lead to noticeable banding issues on Chrome and Safari browsers

The title pretty much sums it up. The first image below is a screenshot of a page that is about 8000 pixels tall, taken in the most recent version of Chrome: On the other hand, this image depicts a different page (with the same CSS), which is only about 8 ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Fade in a CSS class using jQuery

I'm attempting to incorporate a basic fadeIn() CSS effect on specific objects that are tagged with the "button" class. My goal is to have the "hoverbutton" class fade in when the object is hovered over, and then fade out when the cursor moves away fro ...

Slideshow through each item using Typescript and Angular8

I came across a solution in this carousel on by one link, but I'm struggling to work with the jQuery code even though I have JQuery installed in my project. For example: const next = jQuery(this).next(); I am looking to convert the JQuery code from ...