JavaScript's jQuery selector retrieves a child element from one location and adds it to a different

Why does the Jquery children selector select the img element, extract it, remove it, and then append it to another div element? Shouldn't it create a copy of the element being appended?

var $anchors = $("#imageGallery a");
var $overlay = $('<div id="overlay"></div>');
$("body").append($overlay);
$anchors.click(function(event){
event.preventDefault();
$overlay.show();
var a = $(this).children();
$overlay.append(a);
});

$overlay.click(function(){
$(this).hide();
});
body {
font-family: sans-serif;
background: #384047;
}
h1 {
color: #fff;
text-align: center
}

ul {
list-style:none;
margin: 0 auto;
padding: 0;
display: block;
max-width: 780px;
text-align: center;
}
ul li {
display: inline-block;
padding: 8px;
background:white;
margin:10px;
}
ul li img {
display: block;
}
a {
text-decoration: none;
}

#overlay{
width: 100%;
height: 100%;
position: fixed;
top: 0;
left:0;
background: rgba(0,0,0,0.7);
display: none;
}
<body>
<h1>Image Gallery</h1>
<ul id="imageGallery">
<li><a href="images/1.png"><img src="images/1.png"></a></li>
      <li><a href="images/2.png"><img src="images/2.png"></a></li>
      <li><a href="images/3.png"><img src="images/3.png"></a></li>
      <li><a href="images/4.png"><img src="images/4.png"></a></li>
      <li><a href="images/5.png"><img src="images/5.png"></a></li>
      <li><a href="images/6.png"><img src="images/6.png"></a></li>
      <li><a href="images/7.png"><img src="images/7.png"></a></li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>

Answer №1

clone() is a powerful function used to duplicate any object and insert it into the DOM. Enhance your copying and pasting skills with appendTo, prependTo, before, and after functions.

append() places the object inside the selected elements. Start with a simple task like adding the element as the last child of the selected elements, but did you know that you can also rearrange objects within the DOM using this function?

Modifications Made

var a = $(this).children().clone();
$overlay.empty().append(a);

Example in Action

var $anchors = $("#imageGallery a");
var $overlay = $('<div id="overlay"></div>');
$("body").append($overlay);
$anchors.click(function(event){
event.preventDefault();
$overlay.show();
var a = $(this).children().clone();
$overlay.empty().append(a);
});

$overlay.click(function(){
$(this).hide();
});
body {
font-family: sans-serif;
background: #384047;
}
h1 {
color: #fff;
text-align: center
}

ul {
list-style:none;
margin: 0 auto;
padding: 0;
display: block;
max-width: 780px;
text-align: center;
}
ul li {
display: inline-block;
padding: 8px;
background:white;
margin:10px;
}
ul li img {
display: block;
}
a {
text-decoration: none;
}

#overlay{
width: 100%;
height: 100%;
position: fixed;
top: 0;
left:0;
background: rgba(0,0,0,0.7);
display: none;
}
<body>
<h1>Image Gallery</h1>
<ul id="imageGallery">
<li><a href="images/1.png"><img src="images/1.png"></a></li>
      <li><a href="images/2.png"><img src="images/2.png"></a></li>
      <li><a href="images/3.png"><img src="images/3.png"></a></li>
      <li><a href="images/4.png"><img src="images/4.png"></a></li>
      <li><a href="images/5.png"><img src="images/5.png"></a></li>
      <li><a href="images/6.png"><img src="images/6.png"></a></li>
      <li><a href="images/7.png"><img src="images/7.png"></a></li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>

Answer №2

Appending elements with jQuery's `append` function will simply move the elements, not clone them. To clone and append elements, you can create a copy of the element and then pass that copy to the `append` function.

var $anchors = $("#imageGallery a");
var $overlay = $('<div id="overlay"></div>');
$("body").append($overlay);
$anchors.click(function(event) {
  event.preventDefault();
  $overlay.show();
  var a = $(this).children().clone();
  $overlay.html(a);
});

$overlay.click(function() {
  $(this).hide();
});
body {
  font-family: sans-serif;
  background: #384047;
}
h1 {
  color: #fff;
  text-align: center
}
ul {
  list-style: none;
  margin: 0 auto;
  padding: 0;
  display: block;
  max-width: 780px;
  text-align: center;
}
ul li {
  display: inline-block;
  padding: 8px;
  background: white;
  margin: 10px;
}
ul li img {
  display: block;
}
a {
  text-decoration: none;
}
#overlay {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.7);
  display: none;
}
<body>
  <h1>Image Gallery</h1>
  <ul id="imageGallery">
    <li>
      <a href="//placehold.it/64?text=1">
        <img src="//placehold.it/64?text=1">
      </a>
    </li>
    <li>
      <a href="//placehold.it/64?text=2">
        <img src="//placehold.it/64?text=2">
      </a>
    </li>
    <li>
      <a href="//placehold.it/64?text=3">
        <img src="//placehold.it/64?text=3">
      </a>
    </li>
    <li>
      <a href="//placehold.it/64?text=4">
        <img src="//placehold.it/64?text=4">
      </a>
    </li>
  </ul>
  <script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
  <script src="js/app.js" type="text/javascript" charset="utf-8"></script>

Answer №3

var $images = $("#photoGallery img");
var $overlay = $('<div id="overlay"></div>');

$("body").append($overlay);

$images.each(function(){
$(this).click(function(event){
event.preventDefault();
$overlay.show();
var img = $(this).children('img').clone();
$('#overlay').html(img);
});
  });

$overlay.click(function(){
$(this).hide();
});
body {
font-family: sans-serif;
background: #384047;
}
h1 {
color: #fff;
text-align: center
}

ul {
list-style:none;
margin: 0 auto;
padding: 0;
display: block;
max-width: 780px;
text-align: center;
}
ul li {
display: inline-block;
padding: 8px;
background:white;
margin:10px;
}
ul li img {
display: block;
}
a {
text-decoration: none;
}

#overlay{
width: 100%;
height: 100%;
position: fixed;
top: 0;
left:0;
background: rgba(0,0,0,0.7);
display: none;
}
<body>
<h1>Photo Gallery</h1>
<ul id="photoGallery">
<li><a href="photos/1.png"><img src="photos/1.png"></a></li>
      <li><a href="photos/2.png"><img src="photos/2.png"></a></li>
      <li><a href="photos/3.png"><img src="photos/3.png"></a></li>
      <li><a href="photos/4.png"><img src="photos/4.png"></a></li>
      <li><a href="photos/5.png"><img src="photos/5.png"></a></li>
      <li><a href="photos/6.png"><img src="photos/6.png"></a></li>
      <li><a href="photos/7.png"><img src="photos/7.png"></a></li>
</ul>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/app.js" type="text/javascript" charset="utf-8"></script>

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

The div is set to a position of absolute, causing the overflow-y property to be set to auto. As a

I am facing an issue with a div that has absolute positioning nested inside other divs. If you take a look at the code snippet below from http://jsfiddle.net/d8GYk/, you'll notice the styling properties applied to the div. <div style="position: ...

Event bubbling does not occur in elements outside of the DOM

I am facing an issue with a DOM element that has not been added to the DOM yet, but I want to trigger a DOM event on it. The event is not supposed to bubble up, however, when using jQuery, it does. This behavior seems odd to me. This strange phenomenon c ...

What is the most effective way to alphabetically organize a Javascript array?

Is there a more professional way to sort people alphabetically by last name in an array? Here is the array I'm working with: const people = [ 'Bernhard, Sandra', 'Bethea, Erin', 'Becker, Carl', 'Bentsen, Lloyd' ...

Seeking the location of the `onconnect` event within the Express framework

With the use of "express," I have implemented a middleware function like so: app.use(function(request, response, next) { console.log(request.headers["user-agent"]); // etc. }); This currently displays the user-agent header in the console for ever ...

Positioning an element absolutely inside a Material-UI React dialog

Currently, I am working on a Dialog component that includes a button located in the bottom right corner. When this button is clicked, it triggers the display of another div containing a list of items. However, I have encountered an issue where the list is ...

Utilizing external libraries in Vue 3 CLI projects

I've been attempting to load modules like Jquery and @tensorflow/tfjs, but I'm having trouble getting them to work. Both have been installed using npm. Everything in my @vue3/cli project works perfectly until I try to import these two modules. ...

How can I incorporate an error page into this Express application?

I'm currently working on an express application that simulates a basic version of Twitter. One feature I'm trying to implement is an error page. This way, if there are any issues with the routing, users will see a friendly message instead of a g ...

Retrieving the current element in the .each() method

Here is some code that I am working with: HTML <div id="step-holder"> <div class="step-no">1</div> <div class="step-dark-left"><a href="#">Basic details</a></div> <div class="step-dark-right">&a ...

Whenever I execute my code, the browser consistently crashes

Here is the code I have been working on: var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg", "image6.jpg", "image7.jpg", "image8.jpg"]; var objects = []; var geometry; while(objects.length < images.length) { va ...

The timepicker is set to increment by 30-minute intervals, however, I would like the last time option to be 11:

I am currently using a timepicker plugin and am trying to set the last available time option to be 11:59pm. Despite setting the maxTime attribute in my code, the output does not reflect this change. Any suggestions on how to achieve this would be highly ap ...

javascript a loop through an array to reassign element ID's

Formulating a form with input elements that are utilizing a jquery datepicker is the current task at hand. Take a look at a snippet of the HTML code for these inputs: <td style="width:15%"><input type="text" name="datepicker" id="Tb3fromRow10"/&g ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

Selenium: Locating the element correctly, yet unable to perform interactions with the input field

When trying to interact with an input field using the provided script: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_ ...

Encountering an error when attempting to parse a JSON Object in Java from an AJAX call

** Latest Code Update ** My JavaScript and Ajax Implementation: $(function() { $("#create_obd").bind("click", function(event) { var soNumber = []; $('#sales_order_lineItems input[type=checkbox]:checked').eac ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

Conclusion of Tour when an event is triggered by the parent view - Intro.js

File Manager - Home Normal https://i.stack.imgur.com/7C5lH.png I primarily utilize AJAX callbacks for most of my content. Whenever I click a link button on the page, it triggers a modal pop-up using jQuery events and a specific class. The Tour Guide implem ...

Passing a DOM element to an AJAX call: a beginner's guide

I have a scenario where I need to modify a select box based on the results of an ajax call. The issue I'm facing is that the dom element loses its scope within the ajax call, making it difficult for me to access its siblings and update them with the f ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

Limiting the zoom in three.js to prevent object distortion caused by the camera

I'm currently in the process of developing a three.js application where I have successfully loaded my STL objects and incorporated 'OrbitControls'. However, I am encountering an issue when attempting to zoom using the middle scroll button on ...

Creating personalized validation for an AJAX popup in the MVC framework

In my MVC project, I am trying to implement AJAX popup with custom validation. I have created a CustomValidator class and overridden the IsValid() method. However, I am facing an issue where the custom validations are not rendering correctly within the pop ...