Remove items from a list by innerHTML in JavaScript

19,451

Solution 1

I believe you you want to remove the element from the DOM not just override the content of div.

The innerHTML property sets or gets the HTML syntax describing the element's descendants. In your case you are just setting the div content:

document.getElementById('div_' + itemid ).innerHTML = "";

If you want to remove element from DOM:

function removeItem( itemid ) {
  var element = document.getElementById('div_' + itemid ); // will return element
  element.parentNode.removeChild(element); // will remove the element from DOM
}

Also style="overflow: hidden; width:820px; height:auto;" will hide the overflowing div but will not scroll it.

If you want it to scroll you can set overflow:scroll.

Solution 2

I believe your issue is that since div tags are block elements, they are still taking up space in the parent div. Like so:

var element = document.getElementById("div_" + itemid); 
element.parentNode.removeChild(element);

Also, this action is a little cleaner in jquery. You may want to look into it for further DOM operations.

Share:
19,451
user2793679
Author by

user2793679

Updated on June 04, 2022

Comments

  • user2793679
    user2793679 almost 2 years

    I'm new here and I'm stuck in my project...

    I need exclude items from a cart on an ecommerce...

    This cart is showed inside a iframe from Fancybox.

    It works, but visually in Chrome, it doesn't. In Firefox and IE it's work fine...

    I have my items in divs named like div_1, div_2, div_3...

    <div id="div_1">
       content...
    </div>
    <div id="div_2>
       content...
    </div>
    <div id="div_3>
       content...
    </div>
    

    To scroll the page, I put all content inside a main div with style.

    style="overflow: hidden; width:820px; height:auto;"
    

    Because the scroll is controled by the iframe(auto) and my main div there is defined value of widht, and height is auto to fit with my content...

    Inside the divs, I have a img from product, name, price and a remove button with this JS:-

    onClick="removeItem(<%=arrayIndexdiv%>)"
    

    And the function:-

    <script>
        function removeItem( itemid ) {
            document.getElementById('div_' + itemid ).innerHTML = "";
        }
    </script>
    

    In other words, the funcion simply erase the div, excluding them from the page...

    When my list itens is bigger than the iframe size, the vert scrollbar appears.

    When I click on remove, the iten is gonne corretly, in all brownsers, but in Chrome, the size of iframe not change, and I have a blank space above all my items, before the footer.

    In IE and Mozilla it's ok, the space doesn't appears, but in Chrome it is there...

    I don't know if I can put here the URL to help more? If I can, please tell me!

    Can anyone help me?

    Sorry my english!

    Thank you GUYS!