Using jQuery, you can easily update the value of the nth-child(n) for a cloned element

Looking to duplicate an HTML element and assign new values to its child elements? Here's my current HTML structure:

<div id="avator" class="avator" style="display:none">
   <label><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f1f3e0fff8f2e3d6f1fbf7fffab8f5f9fb">[email protected]</a></label>
   <i class="fa fa-close"></i>
</div>

I'd like to clone this element, update its CSS, and modify the label content. My jQuery script currently reads as follows:

  $(document).ready(function () {
      $("#addEmailBtn").click(function () {
        var email = $("#emailInput").val();
        var $clone = $("#avator").clone();
        $clone.children(':nth-child(0)').val(email);
        $clone.css("display", "block");
        $clone.appendTo("#participantsDiv");
     });
  });

However, it doesn't seem to be updating the value within the label element as intended.

Answer №1

Values are not associated with labels; they are typically used for input elements. Instead, utilize .text().

Avoid using :nth-child(1); opt for .eq(0) instead.

$(document).ready(function() {
  $("#addEmailBtn").click(function() {
    var email = $("#emailInput").val();
    var $clone = $("#avator").clone();
    $clone.children().eq(0).text(email);
    $clone.show();
    $clone.appendTo("#participantsDiv");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="avator" class="avatar" style="display:none">
  <label><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e4e6f5eaede7f6c3e4eee2eaefade0ecee">[email protected]</a></label>
  <i class="fa fa-close"></i>
</div>

Email: <input id="emailInput" type="text">
<input type="button" id="addEmailBtn" value="Add email">
<br>
Participants:
<div id="participantsDiv"></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

Managing the vertical positioning of grid items: tips and tricks

Is there a way to make the hexagons in my grid responsive to the layout, so that their height and width remain fixed relative to their container? Currently, they are overflowing from the grid container as shown in this jsfiddle: https://jsfiddle.net/gv5wc1 ...

Header element not keeping the navbar at the bottom

My goal is to attach this navigation bar to the bottom of a header, but it's sticking to the top instead. I want the navigation to remain at the bottom of the header even when the user scrolls down. Currently, both the header and navigation are set t ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

Implementing a distinct approach to adding margins to div boxes using

Hello, I've been experimenting with the developer tools in Google Chrome to add margins to my navigation bar. The goal is to create gaps between the boxes. Any assistance would be greatly appreciated! http://jsfiddle.net/3jp1d0fe/8/ CSS div.contain ...

What is the best method for sending form data and dropzone files simultaneously through AJAX?

Just starting out in the world of jQuery and Dropzone! I've run into a problem with dropzone.js. I need to send form data (such as custom name, ID, DOB, etc.) along with image files that are dropped into the dropzone. Can anyone help me figure out h ...

Counting the number of PHP inputs in a field

Hello, I am using a PHP script from Steve Dawson's website. To display the output on my HTML page, I am utilizing this AJAX script: <script> $.ajax({ type:'GET', url:'http://www.solariserat.se/count.php', data: ...

Uploading a single image using JSON in an MVC API

How can I upload an image as JSON in an API? I need to upload a file to the server folder and save the file path in an object of a class after uploading the image. var data = $('#myForm').serialize(); $.ajax({ url: "/api/CompaniesApi/"+id, ...

The FullCalendar VDOM has been successfully loaded

After loading Full Calendar version 5.5.1, I encountered the error message "FullCalendar VDOM already loaded." Despite searching online, I was unable to find a suitable solution for this issue. I am utilizing NPM as my web pack build system for this proj ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

The transparent overlay div does not activate when clicking on a button in Internet Explorer 10

While tidying up my CSS and JavaScript, I may have gone a bit overboard. The code seems to work fine on Chrome, Safari, and Firefox, but it's causing chaos in IE10. Check out the code here <div id="bgmbutton1"> <img id="button1" src ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

JQuery syntax for adding a comma before the first element in an array

When I insert data into an array, the output in my console includes a comma before the first element (9). How can I remove this comma from the first element using the provided code snippet? ,9,My firstname,My lastname,<a href="/cdn-cgi/l/email-protecti ...

Center a vertically aligned element following a heading, with the content dynamically generated and enclosed in a fixed container

My mind is racing with this problem and I'm not sure if it's solvable, but before throwing in the towel, I thought I'd seek help from the Internet Gods. Here's a visual representation of what I'm aiming for: I want the text to al ...

unexpected issue when trying to append a child element after creating its innerHTML

Upon executing this script, I expect to see the initially empty div with id="checkboxes" transformed into: <div id="checkboxes"> <label><input type="checkbox">option1</label> <label><input type="checkbox">opt ...

Can Bootswatch be installed using a package manager?

I have recently launched a small asp.net core website. Right now, all JS/CSS imports are from NPM and I am using webpack to bundle them together. Instead of sticking with the standard bootstrap template, I wanted to switch to bootswatch paper, but unfortu ...

What is the maximum number of files that FileUploader can accept when multi-select is enabled?

I encountered the following issue: A first chance exception of type 'System.Web.HttpException' occurred in System.Web.dll Additional information: Maximum request length exceeded. while attempting to upload 250 JPEG files, each around 98 KB in ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

`The height attribute of the textarea element is not being accurately adjusted`

When I tried to match the width(178px) and height(178px) of my table to the width and height of a text area upon clicking a button, I encountered an issue. While setting the width works perfectly fine, the height is being set to only 17px. It seems like ...

Modify the HTML based on the width of $(window)

I have a header bar with three columns. When the window width is less than 767px, I need to change the content of these columns. HTML: <div class="header"> <div class="col-xs-4" id="tab1">Original Text</div> <div class="col-x ...

Unable to select the option in select2

While attempting to implement select2 jQuery, I encountered an issue where the data retrieved from the database was displayed properly as I typed in the input field and scrolled through the options, but I was unable to click on any of the displayed data. I ...