Robert002
Robert002

Reputation: 73

How to select several elements in an array?

How can I hide from the third paragraph to the last one? So far I managed to hide only the first one:

<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>

<script>
document.getElementsByTagName("p")[2].style.display="none";
</script>

Upvotes: 0

Views: 123

Answers (2)

David Thomas
David Thomas

Reputation: 253308

My first thoughts would be to use CSS directly:

p:nth-child(n + 3) {
    display: none;
}

JS Fiddle demo.

Or using plain JavaScript:

var pElems = document.getElementsByTagName('p');

for (var i = 2, len = pElems.length; i < len; i++) {
    pElems[i].style.display = 'none';
}

JS Fiddle demo.

Of course, just because it's possible (and yes, you can do this, but that doesn't mean you should), we could also extend the Array prototype, and make use of slice, and call:

Array.prototype.css = function (prop,val) {
    var self = this;
    for (var i = 0, len = self.length; i < len; i++) {
        self[i].style[prop] = val;
    }
    return self;
};
[].slice.call(document.getElementsByTagName('p'), 2).css('display','none');

JS Fiddle demo.


Edited in response to question, left in the comments (below), by the OP:

what would be the shortest [JavaScript] to hide just the last one <p>?

I don't often enter into 'shortest' competitions (redolent of code golf, though the techniques are often impressive); however the simplest approach is as-written in the comment:

var pArray = document.getElementsByTagName("p");
pArray[pArray.length-1].style.display="none";

I originally suggested using pop() (forgetting that a NodeList doesn't have a pop() method) So, to further the above prototype-extending approach (and avoiding re-creating pop(), mainly because slice() seemed to be far more useful in later situations:

Array.prototype.css = function (prop,val) {
    var self = this;
    for (var i = 0, len = self.length; i < len; i++) {
        self[i].style[prop] = val;
    }
    return self;
};

NodeList.prototype.slice = function (a,b) {
    return [].slice.call(this, a, b);
}
var pArray = document.getElementsByTagName("p");

pArray.slice(-1).css('display','none');

JS Fiddle demo.

References:

Upvotes: 1

adeneo
adeneo

Reputation: 318182

As it's tagged with jQuery:

$('p:gt(1)').hide();

:gt = Select all elements at an index greater than index within the matched set (zero based)

Upvotes: 3

Related Questions