Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append fails to do so!

$(()=>{

    $('button').click(function appendizing(){
        for(let i=1; i<=9; ++i)
             $('<div></div>').addClass('box').css("backgroundColor", "wheat").appendTo('.container');
    });

});
.container{
    font-size: 0px;
    border: 1px solid blue;
    width: 120px;
    height: 120px;
}

.box{
    display: inline-block;
    width: 40px;
    height: 40px;
    border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>

<button>appendDiv</button>

now look at this APPEND method usage ->

$(()=>{

    $('button').click(function appendizing(){
    for(let i=1; i<=9; ++i)
$('.container').append('<div</div>').addClass('box').css("backgroundColor", "wheat");
    });

});
.container{
    font-size: 0px;
    border: 1px solid blue;
    width: 120px;
    height: 120px;
}

.box{
    display: inline-block;
    width: 40px;
    height: 40px;
    border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>

    <button>appendDiv</button>

Can anyone explain why this difference occurs? Please elaborate...

Answer №1

Take a look at this

$(()=>{

    $('button').click(function createDiv(){
    for(let j=1; j<=8; ++j)
$('.container').append($('<div></div>').addClass('box').css("backgroundColor", "lightblue"));
    });

});
.container{
    font-size: 0px;
    border: 1px solid red;
    width: 100px;
    height: 100px;
}

.box{
    display: inline-block;
    width: 30px;
    height: 30px;
    border-radius: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>

    <button>Create Div</button>

Answer №2

  1. You seem to have missed closing the div tag.
  2. The classes and styles are being added to the container, not to the appended div elements. Make sure to specify them inline during appending or element creation before appending.

$(()=>{

    $('button').click(function appendizing(){
    for(let i=1; i<=9; ++i)
$('.container').append('<div class="box" style="background-color: wheat;"></div>');
    });

});
.container{
    font-size: 0px;
    border: 1px solid blue;
    width: 120px;
    height: 120px;
}

.box{
    display: inline-block;
    width: 40px;
    height: 40px;
    border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container"></div>

    <button>appendDiv</button>

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

Interacting with a PostgreSQL database using the node-postgres library

Is it necessary to use pg.connect() every time I want to query the database? Upon reviewing the GitHub page and wiki, I noticed that the examples demonstrate a query within the pg.connect callback function as shown below: // This code initializes a connec ...

Stop the Router from Displaying the Page momentarily prior to Redirecting

Currently, I have set up a session context for my NextJS application where users accessing pages within the /app/ directory are required to undergo an authorization check before being granted access. Although the logic is functioning correctly in redirect ...

What is the best way to create a mock URL in axios for unit testing purposes?

Scenario In this application, the URL is only accessible in production and cannot be accessed locally. During unit testing, it becomes necessary to mock the response from that URL. Solution Refer to this helpful tutorial for guidance. Current Implement ...

Stop all animations in JS and CSS

Looking for a way to halt all CSS and JavaScript animations, including canvas and webGL effects, on a specific webpage. Some animations can cause slow performance on certain browsers like Opera and Firefox, so I'm seeking a code snippet or guidance o ...

jquery logic for iterating through all elements in a select menu encountering issues

In search of a solution to iterate through all options in a dropdown list using code, comparing each to a variable. When a match is found, I aim to set that particular value as the selected item in the dropdown and then exit the loop. Here's what I&ap ...

Verify the presence of a specific number of images, and store them in an array

Currently, I am attempting to utilize jQuery to determine if an image exists within my domain, in order to then store them in an array. Below is the code I am using: jQuery(document).ready(function($) { var images = new Array();    var flag = true; ...

Executing the Npm audit fix --force command will automatically implement its own suggestions

Despite coming across countless similar questions, none of them have been helpful in addressing my issue. I am working on resolving critical vulnerabilities. I have executed npm update, npm audit fix, and npm audit fix --force multiple times, but the prob ...

WebSocket connection issues are being experienced by certain users

While using socket.io, I encountered an issue where some users were unable to send messages with the message "I can't send a message why?". After researching the problem, it seems that the firewall or antivirus software may be blocking websockets. If ...

Styling with CSS to show an image and text on the same line

I would like to show text and image on the same line, with the image slightly above the text. View Demo html img.del { display: inline-block; float: right; cursor: pointer; margin-right: 74% } .astext { text-align: left; margin-le ...

What is the best way to align content in the left center of a Paper component and ensure it stays that way on smaller devices?

Recently, I've been developing a component for my Goal Sharing social media platform. Here's what I have accomplished so far: https://i.stack.imgur.com/UDRim.png In an attempt to position the Avatar component along with two typography component ...

Top method for organizing an array based on an object's property and displaying the outcome

I encountered a problem for which I couldn't find an immediate solution. I have an array of objects representing products, with each product having a category property. My goal is to group these products by their categories. After some trial and error ...

Is it true that .done function cannot be used in an ajax callback?

After adding .done to my ajax callback, I am encountering the following issue: Error: Object doesn't support this property or method This error is being displayed in the file myPage.aspx: function myFunction(albumNb) { alert("START myFun ...

What are the appropriate HTTP methods to use when entering and exiting a chat room?

What are the appropriate HTTP methods to use when joining and leaving a chat group? Currently, I am using the following methods which interact with the database. chatRoom.route('/') .get(chat.getChats) // retrieve all group chats .post(c ...

Error in Docker: Unable to resolve due to sender error: context has been terminated

After attempting to build my docker image for the project in VS Code terminal, I ran into an error. What are some possible reasons for this issue? Along with this question, I have also shared a screenshot of the error logs. ERROR: failed to solve: error ...

The Angular scope remains stagnant even after applying changes

Having trouble updating a variable in the ng-repeat loop <div ng-controller="MapViewCtrl"> <a class="item item-avatar" ng-href="#/event/tabs/mapView" > <img src="img/location.jpg"/> <span cl ...

I'm currently facing difficulties trying to implement AJAX with JavaScript and PHP as the desired output is not being

My query is quite straightforward - why isn't the code functioning properly? I am attempting to have the text echoed in PHP displayed inside a div with the ID of "show". Interestingly, this works with a txt file but not with PHP or any other type of f ...

What could be causing the "module not found" error even after ensuring multiple times that the module is present?

Currently, I am attempting to perform a Google search programmatically using the node module google-search-results-nodejs. Despite my efforts, I continuously encounter the error "not found." My development environment is Gitpod's online workspace, and ...

Step-by-step guide on repairing a countdown clock using JavaScript, HTML, and

I'm having issues with my JS on my website. I am new to this and currently in the process of setting up a website. I want to add a timer to show when the site will be active. It seems like there is an error somewhere in the JS code that I can't ...

Successfully updating a document with Mongoose findByIdAndUpdate results in an error being returned

findByIdAndUpdate() function in my code successfully updates a document, but unexpectedly returns an error that I am having trouble understanding. Below is the schema that I am working with: const userSchema = mongoose.Schema({ phone: String, pas ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...