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

Trouble with Component Lifecycle (ComponentDidMount) activation while switching tabs in TabBar?

After implementing the react-native-tab-navigator library to navigate between components, I encountered an issue where the componentDidMount lifecycle method works only once. I have reached out for help by posting a query on Github and have also attempted ...

Images within the signature are not appearing as intended

Trying to find a way to display a company logo in an email signature without it being blocked by default on different email clients. Initially, I attempted uploading the image to the company website, but encountered the following error: So, I decided to t ...

How can we trigger a function once the API requests within a for loop have completed?

Within this for loop, a maximum of 'time' iterations are specified. With each iteration, a GET call is made to retrieve data that must be added to the obj object. I am seeking a method to determine when all 3 GETS have been completed along with ...

"When using Webpack and Sass, the background image specified with background: url() is processed correctly. However, when using webpack-dev-server, the image is

Currently, I am utilizing Webpack 2 in conjunction with webpack-dev-server and Sass loader. Here is my current configuration: { test: /\.scss/, loaders: [ "style", { loader: "css", query: { modules: false, sourceMap: true } }, ...

Utilizing JavaScript to analyze and interact with a website using Selenium's ghost drivers

Currently, I am attempting to scrape the second page of Google search results using Ghost driver. To achieve this, I am utilizing JavaScript to navigate through the HTML source of the search results page and click on the page numbers at the bottom with G ...

Sending a POST request to a PHP file in React: A Step-by-Step Guide

Just starting out with reactjs and trying to figure out how to send an ajax request to a server (php file). Here's the structure of my project: check it out here src/index.js import React from 'react'; import ReactDOM from 'react-dom& ...

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

What is the best way to retrieve the initial <ul> element from a JavaScript document?

Just to clarify, I'm looking to target a specific div with a class and the first <ul> from a document (specifically in blogger). Currently, I have a JavaScript function that grabs the first image and generates a thumbnail as shown below: //< ...

Is there a jQuery function that can produce repeated output and append content with each successive click?

Attempting to implement a dynamic searchbar with various parameters has led me to explore using jQuery to load and clone the searchbar file in order to append it to the body dynamically. I have made several attempts to modify selectors without achieving t ...

Encountering an ongoing problem with trial repetition in JsPsych, which is causing the looping to continue endlessly without

As a beginner in JsPsych, I'm diving into creating a basic math quiz task to sharpen my skills. The goal is to generate random math questions as prompts and stop the task after 10 correct answers. I've managed to code that selects random math pro ...

How I am able to access this.state in React without the need for binding or arrow functions

Understanding the concept of arrow functions inheriting the parent context is crucial in React development. Consider this React component example: import React, { Component } from 'react'; import { View, Text } from 'react-native'; i ...

A guide to eliminating duplicate values within an array and across multiple arrays with the help of jQuery

Looking for assistance with jQuery to find and alert repeated values in my code. Below are example arrays: a1 = {1,2,3,4,5,6,4} a2= {9,8,7}, a3= {a,b,c,d,e,7} I want to identify the value 4 in array "a1" and give an alert, as well as identify the value ...

Prevent JSON.parse() function from stripping away any trailing zeros in a JSON string dataset

After creating a JSON string, I encountered an issue where the values were not being parsed correctly. Here is the code snippet: <script> var string = JSON.parse('{"items":[{"data":[5.1]}, {"values":[5.10]}, {"offer":[3.100]}, {"grandtotal":[12 ...

Having an issue with a cropped CSS box?

I have created a CSS box with a red background color, but for some reason the bottom left corner is being cut off. Can you provide an explanation for this issue? (Refer to the image below) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ...

Tips for changing the color of shapes when hovering over an image state

I have arranged three images in a column and applied column-count: 3; along with setting border-width for those images. Now I am curious about how to create the hover state for these images. Here is the HTML code snippet: <div class="wrap"> < ...

Troubleshooting: ReactJS CSS Class Issue

I'm fairly new to working with ReactJS and I've encountered an issue while trying to create a class for a specific form. Below is the code I've written: import React, { Component, PropTypes } from 'react'; import s from './s ...

Hidden menu does not work with Jquery

As I work on creating a responsive website, I am faced with the challenge of implementing a menu that only opens on mobile devices when clicked. I came across some code on Stackoverflow that I thought would solve this issue for me. However, I seem to be en ...

Adjust THREE.PerspectiveCamera's distance without altering its viewing orientation

I have a PerspectiveCamera in THREE.js positioned somewhere in space as a child of a mesh. The camera is currently looking at the mesh with local coordinates [0, 0, 0]. I am looking for a way to change the distance of the camera from the mesh without chang ...

Learn how to effortlessly integrate and utilize a bpmn file in a Vue component by leveraging the raw-loader

As a newcomer to bpmn-js, I am facing the challenge of importing and utilizing a .bpmn file within a vue.js component (BPMNViewer.vue). Despite my efforts in researching, I could only find recommendations to use the raw-loader. Consequently, I am currently ...