Employing jQuery to add an element as a sibling rather than a child node

I'm having trouble finding the specific functionality I need. My goal is to add sibling DOM elements to a disconnected node.

From what I gather, it should be possible with either .after() or .add(), but for some reason both methods are not working as expected:

var $set = $('<div class="parent"></div>');
    $set.add('<div class="child"></div>');
    $set.add('<div class="child"></div>');
    $set.add('<div class="child"></div>');
$('body').append($set);

http://jsfiddle.net/kh9Uj/17/ and http://jsfiddle.net/kh9Uj/19/

When I chain the .add() method, like this:

$('<div class="parent"></div>')
    .add('<div class="child"></div>')
    .add('<div class="child"></div>')
    .add('<div class="child"></div>')
.appendTo('body');

http://jsfiddle.net/kh9Uj/23/

However, chaining does not work with .after(). Unfortunately, in my application, chaining is not an option. How can I achieve this?

Edit made to correct the class/id issue.

Answer №1

The variable does not get updated by the set operation.

var $set = $('<div id="parent">0</div>');
$set = $set.add('<div id="child1">1</div>');
$set = $set.add('<div id="child2">2</div>');
$set = $set.add('<div id="child3">3</div>');
$('body').append($set);

Chaining is effective because all elements are added to the same object.

var $set = $('<div id="parent">0</div>')          
               .add('<div id="child1">1</div>')   
               .add('<div id="child2">2</div>')   
               .add('<div id="child3">3</div>');
$('body').append($set);

However, using add places elements as "siblings" when appended.

<parent />
<child1 />
<child2 />
<child3 />

If you want the "child" elements to be children of "parent," use append instead.

var $set = $('<div id="parent">0</div>');
$set.append('<div id="child1">1</div>');
$set.append('<div id="child2">2</div>');
$set.append('<div id="child3">3</div>');
$('body').append($set);

This will result in:

<parent>
    <child1 />
    <child2 />
    <child3 />
</parent>

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

Add additional code to each link within a specified div element

I am looking to add a code at the end of all links with an mp3 extension within a specific div. Below is the code I have been attempting to use: $("#Temp_Div").find('a[href$="mp3"]').append('<a class="mp3play" href="javascript:Play(&apo ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

A valid path is required in the form of a string when working with the HTTP module in Node.js

Currently, I'm working on an update checker that doesn't involve downloading the update. My main goal is to compare the version in the package.json file on GitHub with the one in my Electron app. However, when using this code, I encountered a "p ...

Java Selenium Javascript executor fails to return desired result

Attempting to execute a javascript function I created to gather all comments from an HTML site using xpath (requirement). The function, when pasted directly into a browser without the 'return' statement, works flawlessly. However, when run th ...

The justify-between utility in Tailwind is malfunctioning

Can someone help me figure out how to add justify-between between the hello and the user image & name? They are in different divs, but I've tried multiple ways without success. I'm fairly new to this, so any advice would be appreciated. This ...

Steps for designing a complete background picture

Seeking to enhance my CSS skills, I've been faced with a challenging task recently. The objective is to create a full-screen background image with centered text overlay. However, the image appears larger than the screen itself. This is my current se ...

Is it possible for the JavaScript DOM API to retrieve the exact casing of attribute and tag names?

Is it possible to retrieve the original casing of an attribute name or tag name from the source? The attribute name is in lowercase The tag name is in uppercase The local element name is in lowercase I am looking for a solution that doesn't require ...

Node.js: Extract the object's name and value that are sent from the frontend

I'm in the process of creating a microservice using nodejs. The request is returning the following JSON. { "distCd": "abcd", "distName": "parentLife Distributor (TOD)", "stateCd": "", "subdistInd": false, "maindistInd": true ...

Utilizing .env Variables in NestJS Main App Module for Establishing Database Connection

I recently embarked on my first NestJS project, where I initially had a hardcoded database connection string in app.module.ts that worked perfectly fine. However, our project requirements called for fetching the database configuration values from environm ...

Managing Events in PHP

As a .net developer working on a php site for a friend, I've been making good progress. However, I have a question - is there something similar to a textchanged event in php? Here's what I'm trying to achieve: I want to dynamically populate ...

When attempting to parse a JSON feed with jQuery and innerHTML, the data fails to display

Having trouble parsing a JSON feed using jQuery and innerHTML, but for some reason it's not working as expected. No errors are being displayed in the console and the feed itself is functioning properly. Not quite sure why this issue is occurring. < ...

A step-by-step guide on smoothly transitioning between elements using Vue-Carousel on a click event

Today marks my first question here and I'm excited! Can anyone guide me on how to implement sliding on click element with Vue-Carousel? I want to slide to the right with just a single click on my input button. Here's the code snippet I have base ...

I currently have a form within a div that is part of a loop to showcase saved data. My objective is to identify any changes made in the form fields so I can detect them effectively

This code is located inside a loop <div class="card card-fluid"> @php $counterId++; $formId = 'startLog'.$counterId; @endphp {!! Form::open(['id'=>$formId,'class'=>'ajax-form','method& ...

Tips for preserving CSS styling following a hover event

While working on implementing a Menu control using jQuery and CSS, I encountered the following issue: Here is a live demo that demonstrates my current problem When I hover over 'Menu Item 1', this item successfully changes its style (background ...

Tips for integrating Server-Side Rendering into an already established React.js app running on Express.js

I am currently working on a React application and I am looking to add SSR using Express.js. Initially, I made a mistake by creating a repository with just a frontend folder containing the entire React app with typescript, babel, and webpack configurations ...

When jQuery adds elements, their response to the .click(function() function can be quite unpredictable

I have set up a JsFiddle to tackle the issue I'm facing. Basically, I am working with a group of checkboxes. Additionally, there is a field where you can add checkbox items to this group. Also, there are arrows that allow for changing the order of th ...

Is there a way to ensure that an image is always smaller than the section it resides in?

Currently, I am in the process of designing a Tumblr theme and have encountered an issue with the avatar image being displayed next to the content. The problem is that the image is larger than the section it's supposed to be contained in, causing it t ...

The error message states: "change is not defined"

I am encountering an issue where I have 4 input boxes triggering a function on keyup using the onkeyup event. Strangely, I keep receiving an error stating that "change" (the function's name) is not defined. Despite correctly defining the function, I c ...

Vue.js: SCSS @import being overlooked

I've found great success using VueJS in two different projects. As I prepare to launch these projects, I'm encountering an issue when generating the files with npm run build. One project, created recently, is working fine. However, the other pro ...

Display problem with Backbone view

I'm having trouble loading views on my page while using underscore for templating. I've tried navigating to the page and loading the view in the initialize function, but neither approach has worked. The majority of this code is from an example. ...