What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed outside of it. I have tried using flex and other CSS properties without success.

//on select
const deleteExisting = document.querySelectorAll('.solidOnClickDelete');
// Item Lists
const itemRows = document.querySelectorAll('.drag-item-list');
const mondayList = document.getElementById('mondaylist');
// Items
let updateOnLoad = false
// Initialize Arrays
let mondayListArray = [];
let listarrays = [];
// Drag Functionality
let dragged;
let updateRow = false;
let dragging = false;
let currentRow;
// Get Arrays from localStorage if available, set default values if not
function getSavedRows() {

    mondayListArray = ['Work 7.00-15.00', 'Doctor visit'];

}
// Set localStorage Arrays
function updateSavedRows() {
    listarrays = [mondayListArray];
    const arrayNames = ['monday']
    arrayNames.forEach((arrayName, index) => {
        //localStorage.setItem(`${arrayName}Items`, JSON.stringify(listarrays[index]))
    });
}
//Filter to remove null from deleted items //
function filterArray(array) {
    const filteredArray = array.filter(item => item !== null);
    return filteredArray;
}
// Create DOM Elements for each list item
function createItemEl(rowEl, row, item, index) {
  // List Item
  const listEl = document.createElement('li')
  listEl.classList.add('day-item');
  listEl.textContent = item;
  listEl.draggable = true;
  listEl.setAttribute('ondragstart', 'drag(event)')
  listEl.contentEditable = true;
  listEl.id = index;
  const divOptions = document.createElement('span');
  divOptions.classList.add('father', 'hidden');
  divOptions.contentEditable = false;
  listEl.onfocus = () => divOptions.classList.remove('hidden');
  listEl.onblur = () => divOptions.classList.add('hidden');
  const iconDelete = document.createElement('i');
  const iconYes = document.createElement('i');
  iconYes.classList.add('far', 'fa-check-circle', 'fa-2x');
  iconDelete.classList.add('far', 'fa-times-circle', 'fa-2x');
  iconYes.setAttribute('onclick', `updateItem(${index}, ${row})`);
  iconDelete.setAttribute('onclick', `deleteItemOnClick(${index}, ${row})`);
  //Append everything // 
  rowEl.appendChild(listEl);
  listEl.appendChild(divOptions);
  divOptions.appendChild(iconYes);
  divOptions.appendChild(iconDelete);
};
// Update Columns in DOM - Reset HTML, Filter Array, Update localStorage
function updateDOM() {
    // Check localStorage once
    if (!updateOnLoad) {
        getSavedRows();
    }
    mondayList.textContent = '';
    mondayListArray.forEach((mondayitem, index) => {
        createItemEl(mondayList, 0, mondayitem, index);
    });
    mondayListArray = filterArray(mondayListArray)
    updateOnLoad = true;
    updateSavedRows();
}
// Delete on click - // 
function deleteItemOnClick(id, row) {
    //let deleteItem = document.getElementsByClassName('solidOnClickDelete');
    const selectedArray = listarrays[row];
    delete selectedArray[id]

    /*
      deleteItem[0].onclick = function () { delete selectedArray[id] };
      console.log(deleteItem[0]);
      updateDOM();*/
    updateDOM();
};
// add To Task Array 
function addToRow(row) {
    const itemText = addTask[row].textContent;
    const selectedArray = listarrays[row];
    selectedArray.push(itemText);
    addTask[row].textContent = '';
    updateDOM();
}
// reBuild Arrays
function rebulidArrays() {
    mondayListArray = [];
    for (i = 0; i < mondayList.children.length; i++) {
        mondayListArray.push(mondayList.children[i].textContent);
    }
    updateDOM();
}
// On Load
updateDOM();
html {
    box-sizing: border-box;
  }
  :root {
  /* Light Theme Default */ 
  /* Main Colors */ 
    --primary-color: rgb(255, 255, 255);
    --primary-variant: #b9b9b9;
    --secondary-color: #5c5c5c;
  /* Text on Main Colors */  
    --on-primary: rgb(54, 54, 54);
    --on-background: rgb(78, 78, 78);
    --on-background-alt: rgba(253, 253, 253, 0.952);
  /* Background */
    --background: rgb(255, 255, 255);
  /* Box Shadow */ 
    --box-shadow: 0 5px 20px 1px rgba(54, 54, 54, 0.5);
  }
  [data-theme="dark"] {
    --primary-color: rgb(39, 39, 39);
    --primary-variant: #777777;
    --secondary-color: #e4e4e4;
    --on-primary: rgb(173, 173, 173);
    --on-background: rgba(255, 255, 255, 0.9);
    --on-background-alt: rgba(0, 0, 0, 0.7);
    --background: #202020;
  }
  body {
    margin: 0;
    color: var(--on-primary); 
     background-color:var(--primary-color);
    font-family: 'Quicksand', sans-serif;
 
  }
 
  .slider.round::before {
    border-radius: 50%;
  }
 
  .main-title {
    font-size: 3rem;
    color: var(--on-background);
  }
  ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
  }
  .main-container {
    margin: 20px;
  }
  
  .days-list {
    display: flex;
    flex-direction:column;
  }
  /* rows / poulation */
  .day-row,.populating-btns {
    margin: 10px 10px;
    background-color: rgba(95, 95, 95, 0.4);
    border-radius: 3px;
    display: flex;
    overflow-x: hidden; 
    flex-wrap: wrap; 
  }
  .dayFunction {
  align-content: center;
  justify-content: center;
  margin-top: auto;
  margin-bottom: auto;
  }
  .Flex-right {
    display: flex;
    float: right;
  
  }
  .Monday-row .header,
  
  .Monday-row .over {
    background-color: var( --on-primary);
  }
  .hidden {
    display: none;
  }

  .day-item {
    margin: 10px;
    padding: 10px;
    height: fit-content;
    background-color:var(--secondary-color);
    color: var(--primary-color);
    border-radius: 3px;
    line-height: 1.5rem;
    letter-spacing: 1px;
    cursor: pointer;
    transition: 1s;
    
  }
  .day-item:focus {
    outline: none;
    background-color: white;
    color: black;
  }
  
  /* Add Button Group */
  .add-btns {
    display: flex;
    justify-content: space-between;
    
  }
  .add-btn {
    margin: 10px;
    padding: 5px 10px;
    display: flex;
    align-items: center;
    cursor: pointer;
    width: fit-content;
    border-radius: 5px;
    transition: all 0.3s ease-in;
    user-select: none;
  }
  .add-task {
    margin: 10px;
    padding: 5px 10px;
    display: flex;
    align-items: center;
    cursor: pointer;
    width: fit-content;
    border-radius: 5px;
    transition: all 0.3s ease-in;
    user-select: none;
    background-color:var(--on-primary);
    color:var(--on-background-alt);
  }
  .add-btn,.add-task:hover {
    background-color: rgba(255, 255, 255, 0.9);
    color: black;
  }
  .add-btn:active {
    transform: scale(0.97);
  }
  .add-btn-extend {
    margin: 10px;
    padding: 10px 40px 10px 40px;
    display: flex;
    align-items: center;
    cursor: pointer;
    border-radius: 5px;
    transition: all 0.5s ease-in;
    user-select: none;
    background-color: rgba(12, 178, 207, 0.603);
  }
  .add-btn-extend:hover {
    background-color: rgba(255, 255, 255, 0.9);
    color: black;
  }
  .solidOnClick , .solidOnClickDelete {
    margin: 10px;
    padding: 5px 10px;
    align-items: center;
    cursor: pointer;
    width: fit-content;
    border-radius: 5px;
    transition: all 0.3s ease-in;
    user-select: none;
    background-color: var(--primary-variant);
  }
  .solidonclick:hover{
    transition: all 0.5s ease-in;
    filter: brightness(95%);
    color: rgb(0, 0, 0);
    background-color: rgba(228, 228, 228, 0.842);
  }
  
  .father {
display: flex;
justify-content: space-between;
}
.fa-check-circle {
  color: green;
}
.fa-times-circle {
  color: red;
}
.hidden {
  display: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css"
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <li class="day-row Monday-row">
        <div id="Mondaycontent">
            <ul id="mondaylist" class="drag-item-list Flex-right" ondrop="drop(event)" ondragover="dropin(event)"
                ondragenter="dragenter(0)">
            </ul>
        </div>

        </div>
        <!--Add Task To Li Later showInputBox()-->
        <div class="add-container">
            <div class="add-item" contenteditable="true"></div>
        </div>
    </li>

</body>
<script src="js.js"></script>

</html>

Answer №1

In the realm of HTML semantics, it's important to note that a list item <li> tag should only be used within an unordered <ul> or ordered <ol> list. The current setup involves a list element acting as a parent container with the class attribute

<li class="day-row Monday-row">
, so it might be more appropriate to switch this to a <div>.

Furthermore, your external JavaScript file enclosed in the <script> tag is positioned outside the <body>, which is considered invalid. To ensure proper functioning, the script should be placed either before the closing body tag </body> or inside the <head> section for the page to load the script successfully.

To address the relocation of the checkmark and red X icons from within the list item content box after clicking on items, a simple solution would involve appending those <span> tags into the outer container known as

<div id="MondayContent">
.

function createItemEl(rowEl, row, item, index) {
   // Selecting the parent container
   const parentDiv = document.querySelector("#Mondaycontent");
   ...
   // Appending icons to the parent container
   parentDiv.appendChild(divOptions);
}

Lastly, utilizing CSS along with some JavaScript will enable you to position the icons appropriately beneath each list item.

Following the execution of the updateDOM() method, the second <span> tag has been positioned below the "Doctor visit" list item. Alternatively, instead of using JavaScript, you could target that tag using a CSS selector like .father:last-child.

// Positioning the icons for the Doctor visit item
const icons = document.querySelectorAll(".father");
icons[1].style.left = "12.5rem";
 /* Styling for the parent div container */
  #Mondaycontent {
    display: flex;
    flex-direction: column;
  }
  #Mondaycontent .father {
    position: relative;
    left: 3rem;
    width: 5rem;
    margin-bottom: .5rem;
  }
  /* Utilize this if styling the second span tag without JavaScript */
  #Mondaycontent .father:last-child {
    left: 12.5rem;
  }

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

Ajax undoes any modifications enacted by JavaScript

When using ajax, I trigger an OnTextChangedEvent. Before this event occurs, there is a Javascript function that validates the input field and displays text based on its validity. However, once the Ajax is executed, it resets any changes made by the Javascr ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

What is the best way to ensure that the swf loads only after all the images and text have loaded completely

Is there a way to use jQuery to control the loading of SWF files on my CMS system? Sometimes when a video is included in the SWF file, it uses up bandwidth and makes the page non-responsive for a while. I would like the SWF files to load after the other co ...

Vue Js does not include images in the dist directory when the build process is completed

In my VueJs 3 project, I am working with a list of PNG images stored in the src/assets/pngs/ directory. Within my Vue component, I use a For loop to dynamically create the list by setting the image name as the source for the img tag. This implementation wo ...

How to customize the color of the clock symbol in a MUI TextField set to type 'time'

<TextField id="endTime" label="End Time" onChange={onEndTimeChange} type="time" defaultValue="16:00" className={classes.textField} /> By using the attribute 'type="time"', an ic ...

What causes the values to constantly change whenever I insert an element into the array?

When I add an element, it automatically replaces all the others. This issue only occurs when I insert the entire object; if I insert a typical element such as an integer or a string, it works without any problems. <body> <div id="app&quo ...

Values in Local Storage are not located upon first attempt, but after a reload they function properly

import {useEffect} from 'react'; import {useRouter} from 'next/router'; const AuthenticationGuard=props=>{ const {children,fallback} = props; const auth = useAuth(); const router=useRouter(); useEffect(()=>{ if(!r ...

Error message: "When using selenium-webdriver in JavaScript, the findElement method for <a> tags cannot be used as a function."&

Seeking the website URL for brand information from this website, I attempted to retrieve it using JavaScript in the console: document.getElementById('phone_number').getElementsByTagName('a')[1].getAttribute('href') However, ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? state constructor(props) { super(pro ...

Tips for injecting an Angular variable into a JavaScript variable

Within my angular controller, I have a function defined as follows: $scope.get_all_places = function () { $http.get("get-all-places").then(function (response) { $scope.selected_place = eval(response.data[0]); }); }; I am trying to assign ...

Utilizing Firebase messaging onMessage function is exclusively enabled within a window environment

Incorporating Firebase Cloud Messaging into my project allowed me to send and receive push notifications successfully. While I can receive the push notifications, unfortunately, I am encountering issues with getting the notification events to function prop ...

Encountering issue with accessing req.body within Next.js 13 middleware function

The issue I am facing in the code snippet below is related to validating the request body against a schema from zod. The current situation leads to failure and catches errors because req.body returns a ReadableStream<Uint8Array> instead of the expect ...

Sort out the table using Javascript and then choose all the checkboxes

I'm struggling with a function in Javascript that will only check checkboxes on visible rows of an HTML table. The table has a checkbox on each row and is filtered based on a textbox above the table. The checkboxes in the table are named chkbuild, an ...

Creating an adaptable image with CSS or Material UI

Is it possible to create a responsive image that shifts from the top right position to the bottom as the size decreases? I've been using Material UI but haven't found any guidance on how to achieve this. .my-photo{ height: 300px; positio ...

Can the MemoryRouter be successfully nested within the BrowserRouter in a React application?

I've been on a quest for some time now, trying to uncover whether it's feasible to utilize MemoryRouter solely for specific routes while maintaining the use of BrowserRouter in general. My goal is to navigate to a particular component without alt ...

Using Javascript to make a call to load or post with jQuery

I'm not dealing with Ajax this time, but rather with JavaScript initializations. Is there a way to automatically update all the loaded elements when using $(element).load(...), in order to, for example, create a rangeInput element from an input type ...

Is there a way to access the origin of an iframe?

I am facing a challenge with an HTML page that includes an iframe. Within the iframe, there are text and buttons that trigger onclick scripts. However, I'm having difficulty retrieving the values of getBoundingClientRect when I specify the ID of the b ...

What is causing the error to appear in the Android web-view when using vue.js?

During the development of my web app using Vue.js, I encountered a strange issue where everything was functioning correctly in desktop browsers but not on mobile devices. To troubleshoot this problem, I decided to install an Android emulator and use remote ...

Is there a way to stop a for-in loop within a nested forEach function in JavaScript?

I am facing a situation with nested loops for (var key in params) { if (Array.isArray(params[key])) { params[key].every(function(item) { let value = something(item.start, item.end); if (value === item.start || value == item.end) { ...

Guide on making a dynamic table with HTML and CSS featuring square cells

Looking to design an 8x8 table using HTML and CSS, with the first column and row functioning as headers (ideally with header row height equal to header column width), and all table body cells being square. Shown below is the current HTML and CSS code: < ...