Why are some existing elements moving when I create a new element, and why are other existing elements getting replaced? [closed]

21 hours ago 3
ARTICLE AD BOX

I am creating an Address Book but I have ran into some issues.

The following is a function that is triggered by a button press:

let addContact = () => { let contactInfo = ['Name', 'Number']; let addressInfo = ['Address Line 1', 'Address Line 2', 'Address Line 3', 'Address Line 4', 'Postcode']; let $newInfo = $('div').addClass('listedAddress').appendTo('#addressList'); $('h6').text(`${contactInfo[0]} - ${contactInfo[1]}`).appendTo($newInfo); $('p').text(`${addressInfo}`).appendTo($newInfo);

My intention is to create a new <div> with the class 'listedAddress' and insert it inside a pre-existing <div> with id 'addressList'. Then I want to add 2 text elements inside the new <div> with the appropriate text shown above.

The following screenshot shows the display when I hit run:

Display when I hit run:

enter image description here

and this screenshot shows the display after I have clicked the button once:

Display when I press the button:

enter image description here

For some reason the existing element is replaced by the new one, as well as there being 3 of the new element despite there being no iteration. I am also confused as to why the search bar and button move to be inside the <div> when i press the button, I tried to give the search bar an absolute position but that hasn't worked.

<head> <title> The Digital Address Book </title> <link href = './addressBook.css' rel = 'stylesheet'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script src = "./addressBook.js"></script> </head> <body> <h1 id = 'mainHeading'> The Digital Address Book </h1> <div class = 'searchBar'> <input type = 'text' placeholder = 'Search...'> <button id = 'addContact'> Add Contact</button> </div> <div id = 'addressList'> <h3 id = 'listTitle'> Saved Addresses:</h3> <div class = 'listedAddress'> <h6 class = 'contactInfo'>1Name - 1Number</h6> <p class = 'address'> 1Address Line 1<br>1Address Line 2<br>1Address Line 3<br>1Address Line 4<br>1Postcode</p> </div> </div> <script> $('#addContact').on('click',function(){addContact()}); </script> </body> .listedAddress { text-align: center; background-color: rgb(236, 235, 220); border: solid 1px black; } .contactInfo { font-size: 20px; margin-top: 2px; margin-bottom: 1px ; } #mainHeading { text-align: center; } .searchBar input[type = text]{ position: absolute; left: 50%; translate: 65% ; width: 30%; background-color: white; color: black; font-size: 20px; border-radius: 6px; } #addressList { position: fixed; top: 10%; left: 50%; translate: -50% 0%; width: 300px; height: 600px; margin: auto; border-color: black; border: solid 5px; background-color: rgb(222, 221, 208); overflow-y: auto; } #listTitle { text-align: center; color: black; } .address { margin-top: 1px; margin-bottom: 2px; }
Read Entire Article