开发者

How to keep only one element if there are more than one

Every time I load a page, I have a random number of elements with the same class and different(random) IDs.

I would like to know how I can keep only one element on the page and delete the others from DOM, according to their class?

Example:

<div id="joke" class="hey"></div>
<div id="joking" class="hey"></div>
<div id="jokes" class="hey"></div>
<div id="joker" class="hey"></div>

I w开发者_如何学Pythonould like to leave only id="joke" where joke (as for the other element's id values) is randomly/dynamically generated.


If you only want to keep the first one:

$('.hey').slice(1).remove();

Reference: .slice(), .remove()


If you want the first one, you can use:

$(".hey").first();

If you want a random element from those matched, you can use the :random filter implemented here and do:

$(".hey:random");


I noticed that there are only answers here that assume jQuery is available. While obviously jQuery is without a doubt perfect and should be elected president I'm going to assume that it's NOT available. Let's do this (removing all except the first element) just using the DOM shall we. (see JSfiddle)

<div id="foo">
    <!-- a jocular comment -->
    <div id="joke" class="hey">1</div>
    <div id="joking" class="hey">2</div>
    <div id="jokes" class="hey">3</div>
    <div id="joker" class="hey">4</div>
</div>

js:

var parent = document.getElementById('foo'),
    elems = parent.childNodes, // live list
    firstElemNode,
    i = 0;

while (elems[i] && elems[i].nodeType != 1) {
    i++;
}

if (elems[i]) {
   firstElemNode = parent.removeChild(elems[i]);
   parent.innerHTML = '';
   parent.appendChild(firstElemNode);
}

We look for the first node that is an element (not a text node or comment node). If we can't find one we are smart enough to do nothing.


var $els = $('.hey');
$els.not($els.eq(Math.floor(Math.random()*$els.length))).remove();

JSFiddle


Try this

$('.hey').not('#joke').remove()


$('div.hey:not(:first)').remove()


To show a random .hey element:

$('.hey').hide();
$('.hey')[Math.floor(Math.random()*$('.hey').length)].show();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜