如果有多个元素,如何只保留一个元素
每次加载页面时,我都会有随机数量的具有相同类和不同(随机)ID 的元素。
我想知道如何根据它们的类在页面上只保留一个元素并从 DOM 中删除其他元素?
示例:
<div id="joke" class="hey"></div>
<div id="joking" class="hey"></div>
<div id="jokes" class="hey"></div>
<div id="joker" class="hey"></div>
我只想保留 id="joke"
,其中 joke
(至于其他元素的 id 值)是随机/动态生成的。
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 would like to leave only id="joke"
where joke
(as for the other element's id values) is randomly/dynamically generated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您只想保留第一个:
参考:
.slice()
,.remove()
If you only want to keep the first one:
Reference:
.slice()
,.remove()
如果您想要第一个,您可以使用:
如果您想要匹配的随机元素,您可以使用实现的
:random
过滤器 此处 并执行以下操作:If you want the first one, you can use:
If you want a random element from those matched, you can use the
:random
filter implemented here and do:我注意到这里只有假设 jQuery 可用的答案。虽然显然 jQuery 毫无疑问是完美的并且应该当选总统,但我将假设它不可用。让我们只使用 DOM 来完成此操作(删除除第一个元素之外的所有元素)。 (参见 JSfiddle)
js:
我们寻找第一个元素节点(不是文本节点或注释节点) )。如果我们找不到一个,我们就足够聪明,什么也不做。
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)
js:
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.
JSFiddle
JSFiddle
试试这个
Try this
要显示随机 .hey 元素:
To show a random .hey element: