查找javascript中没有数据属性的所有元素 [英] Find all elements in javascript that do not have a data- attribute

查看:80
本文介绍了查找javascript中没有数据属性的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到没有数据属性的 $('。post-content')中的所有元素。我试着说像 if(!$('。post-content p')。attr('data-example')){...}

I need to find all elements in $('.post-content') that do not have data attributes. I tried to say something like if (!$('.post-content p').attr('data-example')) { ... }

但显然这不起作用。那么我该怎么做呢:

But obviously that does not work. So how would I do the following:

查找属于.post-content的所有p标签,这些标签没有数据属性并将其删除。

我认为它很直接,但所有堆栈问题和文档,jquery和互联网都有如何添加,如何查找,如何为数据属性添加一个值

I think its very straight forward, but all the stack questions and docs, and jquery and the internet just has "how to add, how to find, how to add a value - to the data attribute"

所以我不太清楚,道歉。在示例中:

So I was not completely clear, my apologies. In the example:

<div class="post-content">
  <p data-attribute="foo">
    <span data-attribute="boo">
     <p>...</p>
    </span>
  </p>
  <p> ... </p>
</div>

我不想嵌套 p 标签,就像你在这里看到的那样,p标签下有一个嵌套的p标签,它有一个数据属性,要删除。只是顶级 p 标签没有数据属性。

I do not want nested p tags, like the one you see here, where there is a nested p tag under the p tag that has a data attribute, to be removed. Just top level p tags that do not have a data attribute.

提供的解决方案往往会删除嵌套和顶部等级。

The solutions provided tend to remove nested and top level.

推荐答案

没有特定的数据属性



您可以结合使用 :not() [attribute] 选择器(小提琴) :

$(".post-content p:not([data-something])").remove();



没有任何数据属性



A。:您可以检查元素中是否有任何内容对象的API / HTMLElement.datasetrel =nofollow> dataset keys()小提琴):

Not having any data attributes

A.: You could check if there's anything in the element's dataset using Object.keys() (fiddle):

$(".post-content p").filter(function(){
   return Object.keys(this.dataset).length === 0;
}).remove();

...或者您可以使用 for ... in

... or you could use for...in:

$(".post-content p").filter(function(){
   for (var prop in this.dataset) {
       return false;
   }
   return true;
}).remove();

注意:根据您需要支持的浏览器,数据集 可能无法使用

B。:您可以简单地遍历元素的 attributes 小提琴):

B.: You could simply iterate over the element's attributes (fiddle):

$(".post-content p").filter(function(){
    return ![].some.call(this.attributes, function(attr){
        return /^data-/i.test(attr.name);
    });
}).remove();

参见: filter() Array.prototype。 some()

这篇关于查找javascript中没有数据属性的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆