Guide to finding the parent component of a particular element?

When the add button is clicked, I am dynamically adding lists and a new button labeled as "New Button" to a web page. My goal is to have a variable printed inside the parent list when this "New Button" is clicked. How can I achieve this functionality?

Below is the CSS code for styling:

.boardcanvas
    {
    position: relative;
    -webkit-box-flex: 1;
    flex-grow: 1;
    background-color: cadetblue;
    }
#board
    {
    white-space: nowrap;
    margin-bottom: 10px;
    overflow-x:auto;
    overflow-y:hidden;
    padding-right: 56px;  
    background-color: rgb(95, 130, 131);
    position: absolute;
    display: inline-flex;

    }
.listwrapper{
    height: 100%;
    width: 270px;
    vertical-align: top;
    white-space: nowrap;
    background-color: rgb(10, 73, 75);
    display: inline-block;
    margin-left:0;
}
.controls{
padding:0;
margin:0;
}

Here's the HTML structure:

<body class = "boardcanvas">
        <div id="board">
            <div class = "controls">
                <button onclick="addme()">
                    Add
                </button>
            </div>

    <div class ="listwrapper" id = "listwrapper" style="display:none">
        <ul id ="selected"   style ="margin:0; padding:0; list-style: none;" 
            class ="consort">
            <div id ="transparent">
                    <button onclick ="new1()">New button</button>
            </div>
        </ul>
    </div>

  </div>
     <a id = "addlist" onclick ="change()" style ="color:inherit" href="#">
                Add a List...
        </a>
 </body>

JQuery script to handle interactions:

<script type ="text/javascript">
    $('.controls').hide();
     function change()
        {   $('#addlist').replaceWith('<div class = "controls"><button 
            onclick="addme()">Add'+
                '</button></div>');

        }   

 function addme()
  {   
  $('#board').append('<div class ="listwrapper" id = "listwrapper">'+
            '<ul id ="selected"   style ="margin:0; padding:0; list-style: 
   none;" class ="consort">'+
                '<div id ="transparent">'+
                '<button onclick ="new1()">New button</button>'+ 
                '</div>'+
            '</ul></div>');
  $('.controls').appendTo('#board');
}

function new1(){
    $("#listwrapper").append("a");
}

Answer №1

It's better to bind the click event directly to the element itself, allowing you to reference its parent using jQuery's .parents() methodReference - jQuery API, like this: .parents('.listwrapper').

Once you have the correct element referenced, you can then use the .append() method to add any necessary content, for example:

$('#board').on('click', '.add-new-button', function(){
  $(this).parents('.listwrapper').append("a");
});

Note:
Since the element is dynamically created and may not be present on page load for direct event binding, it's recommended to delegateReference - jQuery API the event handler to the closest containing element that exists during page load, such as #board, and then target the event trigger or selector parameter, like .add-new-button.

Event handlers are only bound to currently selected elements; they must exist at the time .on() is called. To ensure elements are present and selectable, place scripts after HTML elements or bind events inside a document ready handler. Alternatively, utilize delegated events to attach event handlers.

Delegated events offer the advantage of processing events from descendant elements added later in the document. By selecting an element guaranteed to be present when attaching the delegated event handler, you can avoid having to frequently attach and remove event handlers.

Reference: Direct and Delegated Events - .on() | jQuery API Documentation

Code Snippet Demonstration:

$('.controls').hide();

function change() {
  $('#addlist').replaceWith('<div class="controls"><button onclick="addme()">Add</button></div>');
}

function addme() {
  $('#board').append('<div class="listwrapper" id="listwrapper">' +
    '<ul id="selected" style="margin:0; padding:0; list-style:none;" class="consort ">' +
    '<div id="transparent">' +
    '<button class="add-new-button">New button</button>' +
    '</div>' +
    '</ul>' +
    '</div>');
  $('.controls').appendTo('#board');
}

$('#board').on('click', '.add-new-button', function(){
  $(this).parents('.listwrapper').append("a");
});
.boardcanvas {
  position: relative;
  -webkit-box-flex: 1;
  flex-grow: 1;
  background-color: cadetblue;
}

#board {
  white-space: nowrap;
  margin-bottom: 10px;
  overflow-x: auto;
  overflow-y: hidden;
  padding-right: 56px;
  background-color: rgb(95, 130, 131);
  position: absolute;
  display: inline-flex;
}

.listwrapper {
  height: 100%;
  width: 270px;
  vertical-align: top;
  white-space: nowrap;
  background-color: rgb(10, 73, 75);
  display: inline-block;
  margin-left: 0;
}

.controls {
  padding: 0;
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="boardcanvas">
  <div id="board">
    <div class="controls">
      <button onclick="addme()">Add</button>
    </div>

    <div class="listwrapper" id="listwrapper" style="display:none">
      <ul id="selected" style="margin:0; padding:0; list-style: none;" class="consort">
        <div id="transparent">
          <button class="add-new-button">New button</button>
        </div>
      </ul>
    </div>

  </div>
  <a id="addlist" onclick="change()" style="color:inherit" href="#">Add a List...</a>
</body>

Updated JSFiddle

Answer №2

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="style.css">
<link href="css/fontawesome-all.min.css" rel ="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<a href="blog/2015/08/jquery-bootstrap-icons.download.html" data-icon="download-alt"></a>
<script>
$('.controls').hide();
function change()
{   $('#addlist').replaceWith('<div class = "controls"><button onclick="addme()">Add'+
                    '</button></div>');
    
}   
var counter =0;
    function addme()
    {  counter++;
      $('#board').append('<div class ="listwrapper" id = "listwrapper'+counter +'">'+
                '<ul id ="selected"   style ="margin:0; padding:0; list-style: none;" class ="consort">'+
                    '<div id ="transparent">'+
                    '<button onclick ="new1()">New button</button>'+ 
                    '</div>'+
                '</ul></div>');
        $('.controls').appendTo('#board');
    
    }

    function new1(){
        $( event.target ).closest( ".listwrapper" ).append("a");
        //$("#listwrapper"+counter-1)
        //alert(counter);
    }
</script>

<body class = "boardcanvas">
    <div id="board">
            <div class = "controls">
                    <button onclick="addme()">
                        Add
                    </button>
            </div>
          
        <div class ="listwrapper" id = "listwrapper" style="display:none">
            <ul id ="selected"   style ="margin:0; padding:0; list-style: none;" class ="consort">
                <div id ="transparent">
                        <button onclick ="new1()">New button</button>
                </div>
            </ul>
        </div>
       
    </div>
      <a id = "addlist" onclick ="change()" style ="color:inherit" href="#">
                    Add a List...
            </a>
</body>

Take a look at the updated code I have provided for you.

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

How can I select the specific element within a class when a particular checkbox is selected?

Having a dynamically generated list of elements, each structured like this: <div class="under-item-description"> <span class="under-compare-price">100</span><span class="under-price">50</span> <span class="under-compar ...

When utilizing customize-cra to modify antd less variables, it results in the generation of numerous redundant CSS files during the build

While utilizing customize-cra to override antd less variable, I have encountered an issue where it generates multiple duplicate CSS files during the build process. According to the documentation provided by antd, if I opt for the default import of CSS by ...

Is there a way to detect when a Bootstrap Alert is displayed?

I am using a flask app that flashes messages to an HTML file. When these flashed messages are caught, they are displayed as a bootstrap alert. Here is an example: {% with messages = get_flashed_messages() %} {% if messages %} {% for message in mes ...

What is the best way to retrieve an object using callback data with jQuery?

Using jquery with a servlet to fetch data from a database. The callback function provides raw information from the database. How can I append these values to select options in jsp? Retrive_country servlet code: String sql1 = "SELECT * FROM state WHERE co ...

How can you stop previously stored information from being displayed when clicking on Json?

I'm facing a simple issue with JSON data Below is the JSON code I am working with: { "id" : "1", "name" : "test1" }, { "id" : "2", "name" : "test2" }, { "id" : "3", "name" : "test3" }, { "id" : "4", "name" : "test4" }, { "id" : "5", "name" : ...

What is causing the modal to fail to open when the button is clicked?

My HTML includes a modal that isn't functioning correctly. <!doctype html> <html lang="en"> <head> <title>Rooms</title> <meta charset="utf-8"> <meta name="viewport" conte ...

Tips for incorporating an anchor tag within an img tag in HTML?

Is it possible to add an anchor tag inside an img tag in HTML? <img src="img.jpg" alt="no img" /> I want to include the following inside the img tag: <a onclick="retake();" > Retake </a> The goal is to allow users to retake a photo by ...

Using jQuery: When the API has loaded successfully, execute the specified function

As I dive into working with a search flight API, my goal is to configure some settings when the API loads. Below is the code snippet for loading the API: skyscanner.load('snippets', '1'); function main(){ var snippet=new skysc ...

Tips for passing several parameters through an AJAX POST call in Yii2 framework

My view consists of a detailview and a gridview. The grid view has check-boxes for all the columns, while the detail view contains the model id. What I need is to select a column from the grid view, and upon clicking on an a link button, send an ajax call ...

Tips for aligning a single item to the center in a Bootstrap navigation bar that has the majority of items on the right

I am attempting to center the text "Welcome:" within the navbar without center aligning the entire navbar. I want the navbar to remain right aligned, but only the "Welcome:" portion should be centered. Here is what I have tried so far... <!DOCTYPE html ...

Navigating to the left while implementing right-to-left formatting on a single webpage

I'm currently working on a website and I decided to make it right-to-left (RTL). Everything looks good on the website, except for one specific page. I'm experiencing some difficulties in implementing RTL on this particular page. Although the ot ...

Utilizing AJAX within a Rails application to dynamically alter a database field without the need for a traditional form

I am facing a scenario where I have implemented a table with certain rows structured as follows: <div class="row chord-table-row" id= <%= "chord-#{chord.id}" %>> <div class="small-1 columns"><%= chord.id %></div> < ...

Utilize CSS to prioritize the image and ensure it is responsive

I'm utilizing the 'featurette' feature in bootstrap. Currently, the page displays text on the left and an image on the right. As you reduce the browser size, they stack on top of each other, with the text appearing above the image. How can I ...

How to center align text in the media-body using Bootstrap 4 Beta

Struggling to vertically align the text in media-body to the middle when using the new Bootstrap 4 beta version. Tried an approach mentioned in this solution, but it didn't work with the latest version of Bootstrap. Attempted using text-center and a ...

Developing a feature that allows users to switch between different sets of information

I'm currently exploring a new project and attempting to design a toggle that switches between monthly and annual payments based on the user's selection, much like the functionality found here: . At present, I have implemented two sets of price c ...

Image Carousel Extravaganza

Trying to set up a sequence of autoplaying images has been a bit of a challenge for me. I've attempted various methods but haven't quite nailed it yet. Take a look at what I'm aiming for: https://i.stack.imgur.com/JlqWk.gif This is the cod ...

Locate the parent element using a unique child element, then interact with a different child element

Can you help me come up with the correct xpath selector for this specific element? The element only has a unique href. Is it possible to locate the element by searching for the text iphone X within the href="#">iphone X and also checking for its paren ...

Tips for avoiding the transmission of className and style attributes to React components

Hey there! I'm working on a custom button component that needs to accept all ButtonHTMLAttributes except for className and style to avoid any conflicts with styling. I'm using TypeScript with React, but I've run into some issues trying to ac ...

What is the best way to present sorted items on a user interface?

I have a unique Med interface containing properties like drugClass, dosage, and name. Using this interface, I created an array of drugs with different attributes. How can I filter this array by drugClass and then display the filtered data on a web page? ...

"Retrieve the position of a contenteditable element while also considering HTML

I've been exploring a method to generate annotations within HTML text using JavaScript. The approach involves the user clicking on a contenteditable <div> and obtaining the cursor's position based on their click. Subsequently, when insertin ...