Ways to remove a row from a div element in JavaScript without relying on tables

Hey everyone, I'm looking for a way to delete a row within a div when a delete button is pressed using JavaScript. The catch is that I need to accomplish this without using a table, only with div elements. Can anyone provide a solution for me?

function Add() {
  var x = document.querySelectorAll(".div1");
  var i;
  for (i = 0; i < x.length; i++) {
    x[i].innerHTML += "<br><br> <input type='text' name='mytext'>";
  }
}

function del() {
  var y = document.querySelectorAll(".div2");
  var i;
  for (var i = 0; i < y.length; i++) {
    y[i].innerHTML += "<br><br><br> <input type='button' value='delete' onclick='removeRow(this)'>";
  }
}


function removeRow(input) {
  input.parentNode.removeChild(input.previousSibling);
  input.parentNode.removeChild(input);
}
#add_Btn {
  float: left;
  margin: 0% 0% 0% 72%;
  border-radius: 25px;
  cursor: pointer;
  padding: 10px;
}
body {
  background: #00ffff;
}
input[type=text] {
  padding: 5px;
  margin: 5px 0px 25px 0px;
  border: 2px solid #ccc;
  border-radius: 5px;
}
input[type=button] {
  padding: 5px;
  border: 2px solid #ccc;
  border-radius: 5px;
  background: #00ff99;
  cursor: pointer;
}
#Wrapper {
  width: 80%;
  margin: 7% auto;
}
.div1 {
  float: left;
  width: 20%;
  background: #4dffc3;
}
.div2 {
  float: left;
  width: 20%;
  background: lightyellow;
}
#div3 {
  float: left;
  width: 20%;
  background: lightgray;
}
#div4 {
  float: left;
  width: 20%;
  background: lightblue;
}
#ClearFix {
  clear: both;
}
<section id="Wrapper">
  <button id="add_Btn" onclick="Add(); del();">Add TextBox</button><br><br>
  <div class="div1">
    <p>This is Div one</p>
  </div>
  <div class="div1">
    <p>This is Div two</p>
  </div>
  <div class="div1">
    <p>This is Div threee</p>
  </div>
  <div class="div1">
    <p>This is Div Four</p>
  </div>
  <span class="div2">
    <p>This is Div Five</p>
  </span>
  <!--<div id="ClearFix"></div>-->
</section>

Answer №1

To achieve the desired outcome, it is essential to create a distinct class for each line and remove them accordingly.

Refer to the example below for guidance on how to proceed:

var cpt = 0;
    function Add()
    {
            var x = document.querySelectorAll(".div1");
            var i;
            for (i = 0; i < x.length; i++) 
            {
                x[i].innerHTML += "<br><br> <input type='text' name='mytext' class='"+cpt+"'>";
            }
    }

    function del()
    {
        var y = document.querySelectorAll(".div2");
        var i;
        for(var i=0;i<y.length;i++)
        {
            y[i].innerHTML += "<br><br><br> <input type='button' value='delete'  class='"+cpt+"' onclick='removeRow("+cpt+")'>";
        }
cpt++;
    }


    function removeRow(input)
    {
var list = document.getElementsByClassName(input);
for(var i = list.length - 1; 0 <= i; i--)
if(list[i] && list[i].parentElement)
list[i].parentElement.removeChild(list[i]);
    }
    #add_Btn
        {
            float:left;
            margin:0% 0% 0% 72%;
            border-radius: 25px;
            cursor:pointer;
            padding:10px;
        }

    body
    {
        background: #00ffff;
    }

    input[type=text]
    {
        padding: 5px;
        margin:5px 0px 25px 0px;
        border: 2px solid #ccc;
        border-radius: 5px;
    }

    input[type=button]
    {
        padding: 5px;
        margin:5px 0px 25px 0px;
        border: 2px solid #ccc;
        border-radius: 5px;
        background:#00ff99;
        cursor:pointer;
    }

    #Wrapper
        {
            width:80%;
            margin:7% auto;
        }

        .div1
        {
            float:left;
            width:20%;
            background:#4dffc3;
        }


        .div2
        {
            float:left;
            width:20%;
            background:lightyellow;
        }

        #div3
        {
            float:left;
            width:20%;
            background:lightgray;
        }

        #div4
        {
            float: left;
            width:20%;
            background:lightblue;
        }

        #ClearFix
        {
            clear:both;
        }
<section id="Wrapper">

        <button id="add_Btn" onclick="Add(cpt); del(cpt);">Add TextBox</button>


        <div class="div1">
            <p>This is Div one</p>
        </div>

        <div class="div1">
            <p>This is Div two</p>
        </div>

        <div class="div1">
            <p>This is Div threee</p>
        </div>

        <div class="div1">
            <p>This is Div Four</p>
        </div>

        <span class="div2">
            <p>This is Div Five</p>
        </span>
        <!--<div id="ClearFix"></div>-->
    </section>

Answer №2

Revise code provided by @HassanSaghir. Omit the <br/> tag in JavaScript and make some adjustments to the CSS.

var counter = 0;

function Add() {
    var elements = document.querySelectorAll(".div1");
    var index;
    for (index = 0; index < elements.length; index++) {
        elements[index].innerHTML += "<input type='text' name='mytext' class='" + counter + "'>";
    }
}

function del() {
    var elements2 = document.querySelectorAll(".div2");
    var index2;
    for (index2 = 0; index2 < elements2.length; index2++) {
        elements2[index2].innerHTML += "<input type='button' value='delete'  class='" + counter + "' onclick='removeRow(" + counter + ")'>";
    }
    counter++;
}


function removeRow(input) {
    var items = document.getElementsByClassName(input);
    for (var i = items.length - 1; 0 <= i; i--)
        if (items[i] && items[i].parentElement)
            items[i].parentElement.removeChild(items[i]);
}
#add_Btn {
    float: left;
    margin: 0% 0% 0% 72%;
    border-radius: 25px;
    cursor: pointer;
    padding: 10px;
}
body {
    background: #00ffff;
}
input {
  display: block; /* new */
}
input[type=text] {
    padding: 5px;
    margin: 5px 0px 25px 0px;
    border: 2px solid #ccc;
    border-radius: 5px;
}
input[type=button] {
    padding: 5px;
    margin: 5px 0px 25px 0px;
    border: 2px solid #ccc;
    border-radius: 5px;
    background: #00ff99;
    cursor: pointer;
}
#Wrapper {
    width: 80%;
    margin: 7% auto;
}
.div1 {
    float: left;
    width: 20%;
    background: #4dffc3;
}
.div2 {
    float: left;
    width: 20%;
    background: lightyellow;
}
#div3 {
    float: left;
    width: 20%;
    background: lightgray;
}
#div4 {
    float: left;
    width: 20%;
    background: lightblue;
}
#ClearFix {
    clear: both;
}
<section id="Wrapper">
  <button id="add_Btn" onclick="Add(counter); del(counter);">Add TextBox</button>
  <div class="div1">
    <p>This is Div one</p>
  </div>
  <div class="div1">
    <p>This is Div two</p>
  </div>
  <div class="div1">
    <p>This is Div threee</p>
  </div>
  <div class="div1">
    <p>This is Div Four</p>
  </div>
  <span class="div2">
    <p>This is Div Five</p>
  </span>
  <!--<div id="ClearFix"></div>-->
</section>

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

What significance does it hold when an unhandled rejection event lacks a reason field?

Our app tracks client-side errors using Rollbar, but we keep encountering a not very helpful error message from Safari and Chrome: [unhandledrejection] error getting `reason` from event Upon investigation, I found that this message is generated by Rollbar ...

What is preventing me from accessing the sub-elements of an AngularJS controller?

I know this question has probably been asked countless times before, but I'm struggling to find the right words to explain my specific issue. Essentially, I'm having trouble accessing something like $ctrl.thing.subelement. However, the following ...

Contrasts in padding arrangements between Firefox and other browsers

Take a look at the following code snippet: https://jsfiddle.net/a13nd32u/3/ #post_part{display:inline;padding:6px 9px;float:right;font-size:15px} select{width:80px;height:21px;padding-right:10px;display:inline} #button1{display:inline;padding-left:10px} ...

The jQuery AJAX call isn't getting the expected response

Having trouble with a specific part of an application I'm working on. I'm trying to make an AJAX request to fetch information from an XML file. The server is supposed to return the information in JSON format. I've used the same code for bot ...

Implementing Cross-Origin Resource Sharing (CORS) in Express.js to facilitate communication between various ports

Struggling to make API calls using React and Axios from my front end (localhost:3000) to my back end (localhost:4567) is proving challenging. The consistent error message I encounter is: The CORS policy is blocking access to XMLHttpRequest at 'localh ...

The odd behavior of how my friends' likes are appearing on Facebook FQL URLs

Hey there! I'm trying to keep track of the number of likes on a specific URL shared by my friends. Here's the code snippet I have: function countURLLikes(url){ FB.api({ access_token:'CAACEdEose0cBABMG67fV8Yn5cHo5fkb ...

when passing a JavaScript symbol in Django's JSON objects, it does not display properly

When working with Django (2.2), my goal is to send a JSON response in this format: return JsonResponse(data, safe=False) Within the data object, there is a value that looks like this: "unit": "\u33A5" (cubic meters). However, ...

Update HTML element using Jquery periodically

I have a PHP script that updates me with the upcoming bus departure time. Currently, I am using jQuery to refresh this information in a div every minute. However, since I know when the data will change (after the bus arrives), I want the div to refresh at ...

Extract the data from a deeply nested key within a JSON object

I'm currently working on a function that takes a key (specified as a string) and retrieves its corresponding values from a given JSON object. Here is the JSON data I am working with: [ { "some_key1": [ {"key": "va ...

The navigation underline stays in place even after being clicked, and also appears below

Take a look at this js fiddle I've managed to create the underline effect on the navigation links when the user hovers over them. However, the underline only stays visible until the user clicks elsewhere on the screen. How can I make it persist as l ...

Converting JSON arrays to integers from strings in JavaScript: A step-by-step guide

When my application receives a Json string from the server (written in Java), I am faced with an issue when retrieving the data in JavaScript. The current format of the data looks like this: var data = [{"value":"3","label": "17 hr"}, {"value":"2", "labe ...

Tips for displaying two input decorations in Material UI beside one another within a text field

In the Text Field demonstration, I noticed input adornments at the start and end. However, I am looking to have two input adornments at the end specifically. I attempted to add them using endAdornment: {InputAdornment InputAdornment}, but encountered an er ...

Disordered block elements

I am having trouble centering a div in my footer. When I try to center it, the div ends up floating on top of the footer instead. Here is the link to the codepen. footer { text-align: center; background-color: grey; position: fixed; bottom: 0; width: 100 ...

Is it possible to create horizontal scrolling lanes using HTML and CSS?

Simple code snippet: <div id="page-wrap"> <div class="post horizontal"> <h2>Headline 01</h2> <div class="entry"> <p>Lorem ipsum dolor...</p> <p class="image"><img class= ...

Experiencing duplicate execution of $onChanges in AngularJS version 1.6

I might be overthinking this, but that's why I'm seeking help. :) Note: In the example below, the controller alias for the component is "ctrl". var ctrl = this; Imagine we have a component with two bindings, one of which is optional: bindings: ...

What is the best way to ensure that my drop down select menu consistently displays the same data even after performing a query with the menu?

Hey there! I'm facing a little hiccup with a drop-down selection box. Here's what I'm trying to do - get someone to log into a database, and then display all available tables in the selection box. Once they choose a table, they hit select an ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...

Play a matching game using CSS3 to match and check tiles

Currently in the process of creating a game using HTML5 and CSS3. I'm working with several divs that have hover-activated CSS3 animations. The game itself is a simple matching tiles/cars game, optimized for Chrome as it currently only supports -webki ...

Generate a fresh JSON object following a click event triggered by an HTTP PUT request

I have the following structure in JSON format: "disputes": [ { id: "", negotiation_type: "", history:{ user_flag: "", created_at: "", updated_at: "", created_by: null, updated_by: null, ...

Tips on altering the quantity of columns in a ul list dynamically

I'm trying to create a list with 2 columns, and I want it to switch to 3 columns when the browser window is wide enough (for example, on a 23 inch monitor). Can this be achieved using CSS or any other method? Here is my current CSS: .search-results ...