How to remove elements with javascript

How to remove item from array by value? [duplicate]

I’ve looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.

I wrote various solutions for this (remove one or multiple values) and this is my ultimate solution (I benchmarked and it is faster than lodash). Have a go: gist.github.com/ardeshireshghi/0d97db4ae09bc2f90609c536fc63c648

I think most clean way to remove items from array is to use ary.filter() method of array. ary.filter(val => val !== ‘seven’ ). This will return new array with all elements expect ‘seven’

37 Answers 37

You can use the indexOf method like this:

var index = array.indexOf(item); if (index !== -1)
var array = [1,2,3,4] var item = 3 var index = array.indexOf(item); array.splice(index, 1); console.log(array)

It would be best to do a check to only splice if different than -1 , there are like millions of options, choose wisely jsperf.com/not-vs-gt-vs-ge/4

Make sure index!==(-1) , i.e. item exists in array, or else you will splice out the last element in array.

var arr = ['three', 'seven', 'eleven']; // Remove item 'seven' from array var filteredArray = arr.filter(function(e) < return e !== 'seven' >) //=> ["three", "eleven"] // In ECMA6 (arrow function syntax): var filteredArray = arr.filter(e => e !== 'seven') 

This makes use of the filter function in JS. It’s supported in IE9 and up.

What it does (from the doc link)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

So basically, this is the same as all the other for (var key in ary) < . >solutions, except that the for in construct is supported as of IE6.

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in construct (AFAIK).

Источник

How to remove an HTML element using Javascript?

What happens when I click the submit button, is that it will disappear for a very very short time and then appear back immediately. I want to completely remove the element when I click the button.

Sorry, it’s of topic but it is actually really funny, that he/she named him-/herself «Newbie Coder» and now the profile has a reputation of around 9000. Asking something in the «good old times» is really profitable nowadays. 🙂

11 Answers 11

What’s happening is that the form is getting submitted, and so the page is being refreshed (with its original content). You’re handling the click event on a submit button.

If you want to remove the element and not submit the form, handle the submit event on the form instead, and return false from your handler:

But you don’t need (or want) a form for that at all, not if its sole purpose is to remove the dummy div. Instead:

However, that style of setting up event handlers is old-fashioned. You seem to have good instincts in that your JavaScript code is in its own file and such. The next step is to take it further and avoid using onXYZ attributes for hooking up event handlers. Instead, in your JavaScript, you can hook them up with the newer (circa year 2000) way instead:

function removeDummy() < var elem = document.getElementById('dummy'); elem.parentNode.removeChild(elem); return false; >function pageInit() < // Hook up the "remove dummy" button var btn = document.getElementById('btnRemoveDummy'); if (btn.addEventListener) < // DOM2 standard btn.addEventListener('click', removeDummy, false); >else if (btn.attachEvent) < // IE (IE9 finally supports the above, though) btn.attachEvent('onclick', removeDummy); >else < // Really old or non-standard browser, try DOM0 btn.onclick = removeDummy; >> 

. then call pageInit(); from a script tag at the very end of your page body (just before the closing tag), or from within the window load event, though that happens very late in the page load cycle and so usually isn’t good for hooking up event handlers (it happens after all images have finally loaded, for instance).

Note that I’ve had to put in some handling to deal with browser differences. You’ll probably want a function for hooking up events so you don’t have to repeat that logic every time. Or consider using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those browser differences for you. It’s very important to understand the underlying stuff going on, both in terms of JavaScript fundamentals and DOM fundamentals, but libraries deal with a lot of inconsistencies, and also provide a lot of handy utilities — like a means of hooking up event handlers that deals with browser differences. Most of them also provide a way to set up a function (like pageInit ) to run as soon as the DOM is ready to be manipulated, long before window load fires.

Источник

Читайте также:  Php exception error info
Оцените статью