Removing nested divs using JavaScript

My website has a nested div structure which contains multiple child divs. Here is an example of the div structure:

<div id="outside-one">
    <div class="inside" id="1"></div>
    <div class="inside" id="2"></div>
    <div class="inside" id="3"></div>
    <div class="inside" id="4"></div>
    <div class="inside" id="5"></div>
    <div class="inside" id="6"></div>
    <div class="inside" id="7"></div>
    <div class="inside" id="8"></div>
    <div class="inside" id="9"></div>
    <div class="inside" id="10"></div>
</div>

I want to remove five specific child divs from this parent div, but I need to keep the first div (with the id 1) intact. My solution is to apply the CSS property display:none to hide the unwanted child divs without deleting them.

Basically, I am seeking a way to hide five divs simultaneously while leaving the first one visible. The challenge is that the child div ids are not always sequential or known ahead of time, making it hard to target them directly in CSS. Additionally, I plan to repeat this action multiple times and I'm unsure if using display:none is the best approach.

Is there a JavaScript solution to achieve this? Thank you.

Answer №1

Retrieve an array of these elements by their class name (or alternatively use getElementsByTagName if they are not assigned a class), then create a loop that begins at 1 (the second element) instead of 0 (the first element) and apply display: none;

var elements = document.getElementById('parent').getElementsByClassName('inside');

for (var i = 1; i <= 5; i++) {
  elements[i].style.display = 'none';
}
<div id="parent">
<div class="inside">1</div>
<div class="inside">2</div>
<div class="inside">3</div>
<div class="inside">4</div>
<div class="inside">5</div>
<div class="inside">6</div>
<div class="inside">7</div>
<div class="inside">8</div>
</div>

Answer №2

Learn how to use the jQuery slice() method in order to extract a portion of element collection.

// select elements between index 1 and 6
$('#outside-one .inside').slice(1, 5).hide()

// alternatively, skip the first child and get the first 5 elements
$('#outside-one .inside:not(:first-child)').slice(0, 5).hide()

$('#outside-one .inside').slice(1,6).hide()

// or


$('#outside-one .inside:not(:first-child)').slice(0,5).hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outside-one">
  <div class="inside" id="1">1</div>
  <div class="inside" id="2">2</div>
  <div class="inside" id="3">3</div>
  <div class="inside" id="4">4</div>
  <div class="inside" id="5">5</div>
  <div class="inside" id="6">6</div>
  <div class="inside" id="7">7</div>
  <div class="inside" id="8">8</div>
  <div class="inside" id="9">9</div>
  <div class="inside" id="10">10</div>
</div>


If you want to target the last 5 elements:

// exclude the initial children and specify a negative value to retrieve the last n elements 
$('#outside-one .inside:not(:first-child)').slice(-5).hide()

$('#outside-one .inside:not(:first-child)').slice(-5).hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outside-one">
  <div class="inside" id="1">1</div>
  <div class="inside" id="2">2</div>
  <div class="inside" id="3">3</div>
  <div class="inside" id="4">4</div>
  <div class="inside" id="5">5</div>
  <div class="inside" id="6">6</div>
  <div class="inside" id="7">7</div>
  <div class="inside" id="8">8</div>
  <div class="inside" id="9">9</div>
  <div class="inside" id="10">10</div>
</div>


UPDATE : In pure JavaScript, achieve the same functionality using the Array#slice method.

// select elements excluding the first child and convert it into an array
// for older browsers, utilize `[].slice.call()` to convert into an array
// after conversion, obtain a subset using slice 
// iterate over the subset and update the display style
Array.from(document.querySelectorAll('#outside-one .inside:not(:first-child)')).slice(0, 5).forEach(function(ele) {
  ele.style.display = 'none';
})

Array.from(document.querySelectorAll('#outside-one .inside:not(:first-child)')).slice(0, 5).forEach(function(ele) {
  ele.style.display = 'none';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outside-one">
  <div class="inside" id="1">1</div>
  <div class="inside" id="2">2</div>
  <div class="inside" id="3">3</div>
  <div class="inside" id="4">4</div>
  <div class="inside" id="5">5</div>
  <div class="inside" id="6">6</div>
  <div class="inside" id="7">7</div>
  <div class="inside" id="8">8</div>
  <div class="inside" id="9">9</div>
  <div class="inside" id="10">10</div>
</div>

Answer №3

Check out this straightforward solution that meets your needs:

    <div class='hidden'>X</div>
    <div class='hidden'>Y</div>
    <div class='hidden' id='2'>Z</div>

<script>
    function displayOnly(id) {
        $('.hidden').not('#' + id).hide();
    }

    displayOnly(2);​
</script>

http://jsfiddle.net/aymansafadi/kReZn/

Answer №4

Working with jQuery:

$("#outside-one").find("div:not(:first)").hide();

If you prefer using vanilla JavaScript, the implementation would be a bit more involved.

Answer №5

Of course, it can be done:

function concealElements(startIndex, numToHide) {
  var elements = $("#outside-one").children();
  for(let i = startIndex; i < startIndex+numToHide; i++){
     $(elements[i]).hide();
  }
}

concealElements(1, 5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="outside-one">
    <div class="inside" id="1">1</div>
    <div class="inside" id="2">2</div>
    <div class="inside" id="3">3</div>
    <div class="inside" id="4">4</div>
    <div class="inside" id="5">5</div>
    <div class="inside" id="6">6</div>
    <div class="inside" id="7">7</div>
    <div class="inside" id="8">8</div>
    <div class="inside" id="9">9</div>
    <div class="inside" id="10">10</div>
</div>

Answer №6

An efficient function designed to conceal a specific range of elements based on provided parameters like selector, from index, and to index. Example of usage:

hideElements('#main-section span', 2, 8)
hides the second through eighth span elements within the #main-section.

function hideElements(selector, startIndex, endIndex){
    $(selector).slice(startIndex, endIndex).hide();
}

Answer №7

One possible solution is to utilize jQuery for achieving this

$('#container-one div').each(function(index){
    if(index > 0 && index < 5){
        $(this).hide();
    }
})

Answer №8

If you're looking for a simple solution to remove the last set of children from a parent element while retaining the first one, check out this code snippet. In this example, I've utilized button clicks to execute the function.

Below is the ES6 variant of the script:

{
    // This initial line is just a quick way to populate child divs!
    let p=document.getElementById("parent"),d=document.createElement("div"),x=Math.floor(Math.random()*(50-6+1))+6;d.append(document.createTextNode(""));while(x--){d.id=`child${x}`;d.firstChild.nodeValue=`Element ${x}`;p.prepend(d.cloneNode(1));}

    // Implementation starts here
    let children=document.getElementById("parent").children,
        length=children.length,
        remove=count=>{
            if(length){
                while(count--&&--length){
                    children[length].classList.add("hide");
                }
            }
            if(!length){
                console.log("All elements have been removed");
            }
        };

    // Event listener to trigger the function
    document.addEventListener("click",event=>{
        let target=event.target;
        if(target.nodeName.toLowerCase()==="button"){
            remove(parseInt(target.dataset.remove));
        }
    },0);
}
*{background:#fff;border:0;color:#000;box-sizing:border-box;font-family:sans-serif;font-size:14px;outline:0;padding:0;}button{background:#000;color:#fff;margin:0 5px 5px 0;padding:10px;}div{border:1px solid;padding:5px;}div:nth-child(n+2){margin-top:5px;}
/** The class to be added to the hidden elements **/
div.hide{
    display:none;
}
<button data-remove="3">Remove 3 Elements</button><button data-remove="4">Remove 4 Elements</button><button data-remove="5">Remove 5 Elements</button>
<div id="parent"></div>

Here's the ES5 version for comparison:

(function(d){
    // Ignore this first line, it's just a lazy way of adding the child divs!
    var p=d.getElementById("parent"),c=d.createElement("div"),x=Math.floor(Math.random()*(50-6+1))+6;c.appendChild(d.createTextNode(""));while(x--){c.id="child"+x;c.firstChild.nodeValue="Element "+x;p.insertBefore(c.cloneNode(1),p.firstChild);}

    // The real code starts here
    var children=d.getElementById("parent").querySelectorAll("div"),
        length=children.length,
        remove=function(count){
            if(length){
                while(count--&&--length){
                    children[length].classList.add("hide");
                }
            }
            if(!length){
                console.log("All elements have been removed");
            }
        };

    // Event listener to trigger the function
    d.addEventListener("click",function(event){
        var target=event.target;
        if(target.nodeName.toLowerCase()==="button"){
            remove(parseInt(target.dataset.remove));
        }
    },0);
})(document);
*{background:#fff;border:0;color:#000;box-sizing:border-box;font-family:sans-serif;font-size:14px;outline:0;padding:0;}button{background:#000;color:#fff;margin:0 5px 5px 0;padding:10px;}div{border:1px solid;padding:5px;}div:nth-child(n+2){margin-top:5px;}
/** The class to be added to the hidden elements **/
div.hide{
    display:none;
}
<button data-remove="3">Remove 3 Elements</button><button data-remove="4">Remove 4 Elements</button><button data-remove="5">Remove 5 Elements</button>
<div id="parent"></div>

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

Issue with Chrome not triggering onMouseEnter event when an element blocking the cursor disappears in React

Important Note: This issue seems to be specific to Chrome Currently, React does not trigger the onMouseEnter event when a blocking element disappears. This behavior is different from standard JavaScript events and even delegated events. Below is a simpli ...

When the browser is refreshed, jQuery will automatically scroll the window down

I created a div that matches the height and width of the window to simulate a "home screen." When scrolling down to view the content, everything works fine. However, after refreshing the browser, it automatically scrolls back to where you were before. I wa ...

Javascript function to deselect all items

One of my functions is designed to reset all checkbox values and then trigger an AJAX request. However, there are instances when the function initiates before the checkboxes have been unchecked. function clear() { $("#a").prop("checked", false); $("#b ...

Tips for positioning an element so that it remains anchored to the content it is placed within

Hey Everyone! I'm struggling a bit with how to position the h2 headings in my code so that they stay fixed in the top right corner of the box while moving along with the rest of the contenthttps://i.stack.imgur.com/OOVaA.png%60 What I'm attempt ...

Is there a way to make those three elements line up in a row side by side?

I'm working on a layout using HTML and CSS that will display two images on the left and right sides of the browser window, with text in between them. I want them all to be horizontally aligned within a container. Here is the code snippet: <div cla ...

Collection of HTML elements that need to stay in the same section

I am struggling to align multiple vertical lines of data on a webpage and keep them together when the page size changes. I've been working with CSS and HTML code but finding it challenging. Any suggestions or alternative approaches would be greatly ap ...

Placement of Buttons Inside a Division Tag

Is there a better way to align button 3 & 4 in a vertical column next to button 1 & 2 without using tables in CSS? See the working example below: https://jsfiddle.net/Jaron787/0te3cs66/1/ Code: HTML <div id="lse" class="display"> <di ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

Populating hidden fields in Javascript with mouseover event trigger - Pre-click action

Seeking a solution for another issue, I stumbled upon the capability to execute JavaScript on mouseover. Here is what I want to execute: $(document).ready(function(){ function myPayment() { var value = document.mortgagecalc.value_input.value; var rate ...

Activate the initial tab in JQuery UI accordion upon initialization

Hello, I have implemented a simple sidenav menu on my website. It consists of parent items and child items structured according to the h3 > div format as suggested by JQuery's documentation. My challenge now is to automatically open the "active" tab ...

How can validation of input fields be implemented in React Js?

Currently, I am dealing with a variable (in my actual application it is an API) named data, which contains nested items. Starting from the first level, it includes a title that is already displayed and then an array called sublevel, which comprises multip ...

Normalization of Firebase Database

Recently, I developed a Tricycle Patrol app designed to address the prevalent issue of reckless tricycle drivers in our city. Users can log in and submit reports through a form that includes fields such as: - created_at - description - lat - lng - plateNu ...

Tips for resolving NPM high severity vulnerabilities related to pollution issues

Every time I attempt to install npm packages, I encounter the same error message indicating "3 high severity vulnerabilities." When I execute the command npm audit fix, I consistently receive this: https://i.stack.imgur.com/3oJIB.png I have attempted to ...

Is there a way to create a soft light blue backdrop for text using HTML and CSS?

Is there a way to create a light blue background effect behind text using HTML and CSS? You can view the image reference here ...

Guide on how to transmit an error message from PHP when handling a jQuery Ajax post request

Greetings! This is my inaugural inquiry, so please understand if I am a bit apprehensive. I am facing an issue in the following scenario... I have an Ajax request structured like this: $.ajax({ url: "test.php", method: "POST", data: { ...

What is the reason for npm and yarn to download multiple versions of jquery?

For the purpose of investigating how package managers like npm, yarn, and cnpm work in Node.js, I conducted an experiment. During the test, I came across two packages: jquery-dreamstream and jquery.tree. Both of them have a dependency solely on jquery wit ...

Having trouble retrieving AJAX response data using jQuery

I have been searching and attempting for hours without success. On my current page, I am displaying basic data from a database using PHP in an HTML table. However, I now want to incorporate AJAX functionality to refresh the data without reloading the page ...

Generating dynamic content in a text field based on user selection from a dropdown menu using PHP

I have a database with two fields: package_title and package_cost. I am currently displaying the package_title in a dropdown menu using a while loop. When a customer selects a package_title from the dropdown, I would like to show the corresponding cost (pa ...

Error: The function $scope.apply is invalid and cannot be executed

I am attempting to display the contacts list after retrieving it using rdflib.js. The data is being loaded and stored in the list within the scope. However, I am running into an issue where the $scope is not updating, and it appears that I may be calling ...