Steven Matthews
Steven Matthews

Reputation: 11325

Selecting multiple, but not all HTML classes

So lets say I want to hide a div or span with CSS of a particular class.

Is there anyway to do so for the first X number of instances, or better yet, do it for all except for the last one? I imagine this would require javascript.

pseudocode I am thinking would look like this

if divname.class = "XYZ" {
select all instances -1
execute code that inserts random programmatic id into each class
execute code that hides all ids except the last one
}

Am I on the right track? Or is there any easier/better way?

Upvotes: 0

Views: 100

Answers (6)

Sarfraz
Sarfraz

Reputation: 382806

Is there anyway to do so for the first X number of instances, or better yet, do it for all except for the last one? I imagine this would require javascript.

You can try:

var elms = document.getElementsByClassName('XYZ'), total = elms.length;

for (var i = 0; i < total; i++){
   elms[i].style.display = 'none';
}

In above loop, i will contain index of each element, you can put condition or rather range to specify which ones to delete. For example, if you wanted to hide all except for last one, you would modify it like:

for (var i = 0; i < total - 1; i++){
   elms[i].style.display = 'none';
}

Upvotes: 0

chrismborland
chrismborland

Reputation: 570

You can use the :last-child selector in CSS to do this.

http://www.w3schools.com/cssref/sel_last-child.asp

Upvotes: 0

Trey Copeland
Trey Copeland

Reputation: 3527

Here ya go - http://jsfiddle.net/uUK6G/

Set all your divs to the same class. Then use jQuery to filter out the last one.

$('.myDiv').filter(':not(:last)').hide();​

Upvotes: 0

phatskat
phatskat

Reputation: 1815

If you were using jQuery...

$('.class_name').hide().last().show();

Upvotes: 0

Ajai
Ajai

Reputation: 3500

You could do something like this,

var class_div = document.getElementsByClassName("class_name");
var i =0;

for(i=0;i<class_div.length-1;i++){
  //do whatever you want with class_div[n-1] elements.
}

I am not sure how you do this with jquery but this is one possible solution for javascript.

Upvotes: 0

josh.trow
josh.trow

Reputation: 4901

If you can use jQuery and its nice pseudo-selectors, you could do something like

$('.question-summary:not(:last)')

You can test on the SO homepage.

Upvotes: 1

Related Questions