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

Can anyone suggest a method to preview a specific image before uploading on Internet Explorer?

One issue I am encountering is that Internet Explorer does not support the Filereader function in JavaScript. My solution was to send the file via ajax to the server, which would then respond with the file's content. Do you think this approach could w ...

What is the best way to assign specific variables in a PHP loop using form input?

Let's say I have a basic HTML form displayed below: <div class="form-group"> <label class="control-label" for="checkboxes" name="industry">How would you classify your business?</label> ...

Checking data input from an external PHP file and validating dynamically added table row values using Ajax

I'm currently working on a form with dynamic values, such as adding table rows on button click using jQuery. Now, I also want to validate the data before inserting it into my database. To achieve this, I am performing validation with an external PHP ...

Is it possible to incorporate Excel files into a web-based system that only supports HTML?

Currently, I am working on an HTML-based system where my supervisor has specified that only HTML can be used to keep things easy and simple. My question is: Can Excel files be added to the HTML-based system, and if so, is it possible to work with, save, a ...

Discover the optimal approach for merging two jQuery functions effortlessly

The initial function (which can be accessed at ) is as follows: $('#confirm').confirm( { msg: 'Before deleting a gallery and all associated images, are you sure?<br>', buttons: { separator: ' - ' } } ); ...

Toggle Form Section Visibility

I am working on a table with five rows that have upload buttons. Each time I submit a row, the page refreshes, but I want to hide all but one row at a time. When the first submit button is clicked, it should show the next row and hide the previous ones. Th ...

Adjustable table region in PHP

I need help with displaying multiple results in a dynamically created table within my program. Even though I want to show around 25 records, the program cuts off after the 5th record, leaving empty space. The issue seems to be that the area does not expand ...

Most Effective Method for Switching CSS Style Height from "0" to "auto"

After coming across a question with no answer that suited my needs, I decided to share the solution I created. In my case, I had a hidden generated list on a page which was initially set with a CSS height of "0" and then expanded upon clicking by transit ...

Refresh a dynamically loaded webpage following an update

Trying to grasp the concept of reloading a dynamic page loaded with AJAX after a record is updated. Here's the jquery script on the page: <script type="text/javascript> function showUser(str) { if (str == "") { $("#txtHint").empty() ...

How do you determine the dimensions of a background image?

My div is a perfect square, measuring 200 pixels by 200 pixels. The background image I've chosen to use is larger at 500 pixels by 500 pixels. I'm searching for a method to ensure that the entire background image fits neatly within the confines ...

What is the best way to update a targeted component in React when triggered by an event handler?

Your goal may seem straightforward, but getting a reference to a specific component using this is proving to be tricky. Here we have our App.js file: import React, { Component } from 'react'; import CoolBox from './coolBox.js'; import ...

JQuery shake effect for dynamic text animation

Hey there! I need some help figuring out how to stop this shaking effect after it shakes three times. Do you think using set or clearInterval could do the trick? Any advice would be much appreciated! function interval() { $('#shake') ...

Can you explain the distinction between using a period in a class selector and not using one?

Could someone please clarify the meaning of the code snippet below? <div class="cls1 cls2">abcd <div class="cls2"> adfffff </div> </div> .cls1 { background-color: yellow; } /*sample1 .cls1.cls2 { color: red; } */ /* ...

Adjusting Image Size based on Window Width for Internet Explorer

Based on the provided code snippet <style> .x{ background: url('img.jpg') no-repeat; background-size: contain; height: 100%; } </style> <div class="x"></div> It is functioning correctly in Chrome and Firef ...

Updating Ajax Data within a LoopExplanation: In this scenario, we

Here is my AJAX function: function updatePrice(id, prid, divid, key, name) { $.ajax({ type: "POST", data: "aid=" + id + "&prid=" + prid, url: '<?php echo base_url('grocery/onchange')?>&a ...

`Open popup to make edits on the form`

I'm new to MVC and trying to grasp the best practices. Currently, I need some guidance as I'm stuck with a certain task. My situation involves an edit form where users can update a person's information and view their current contacts. These ...

Utilize the power of jQuery's AJAX capabilities

Is it normal for a jQuery AJAX request to take between 1-2 seconds before receiving a response? Is there any way to minimize this delay? The response type is JSON and the HTML code is small. Thank you! ...

Should PHP be avoided in CSS files?

I've recently developed a CSS page named style.php and at the beginning, I included this line: <?php header("Content-type: text/css"); ?> What are your thoughts on this approach? Is it considered a bad idea? The reason behind doing this is tha ...

Delete entries in table based on user-provided criteria

Hello there, I'm new to this community and seeking some assistance. I am currently learning jQuery/Javascript and have encountered a problem that has me stumped. The issue arises with a table where rows are generated based on a user-selected number f ...

Transform and command the data acquired through an AJAX request using jQuery

My code includes an AJAX call using jQuery: $('.add a').click(function() { $.ajax({ type: 'POST', url: '/api/fos', context: this, datatype: 'html', success: function(data) ...