Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - jQuery Select Element that has no Class or ID

Trying to find a selector to get all elements that have both no class, and no id set to them.

So far I have 2 different outputs depending on if there is a space in the selector:

                                      // outputs
        var noID = $('*:not([id])');// 144 - may have a class
        var noClass = $('*:not([class])');  // 100 - may have an id

        var withSpace = $('*:not([id]) *:not([class])'); // 99 ?
        var noSpace= $('*:not([id])*:not([class])'); // 84 ?

Which one is correct, my guess is the noSpace - but I don't know. Anyone tried this before?

My guess is that with the space, the selector is going inside the tag that has no ID, and selecting the children elements that have no class associated with them.

And the noSpace result is the correct one, as it selects only the elemets that have both no class, and no id.

Can someone verify? Thanks!


Answer

Use this selector to find elements that have neither a class, or an id associated with them.

$('*:not([id]):not([class])');

bonus: $('body *:not([id]):not([class])'); - If you only want to deal with the actual content

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

withSpace - $('*:not([id]) *:not([class])'); will find all elements with no class that are inside an element without an ID. Putting a space in the selector is like calling find seperately.

You could change noSpace to be this instead and still get the right result:

var noSpace= $('*:not([id]):not([class])'); // second * not needed

JSFiddle used for testing


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...