如何用jQuery精确匹配Div类?新手求助实现精准元素选择
Hey there! I totally get where you're coming from—class selectors in jQuery can feel tricky when you need exact matches, especially when elements share most classes but have extra ones. Let's break down how to target each div perfectly.
Target the first div (only plugin-container and plugin-news_home_feature)
Your original selector ($('div.plugin-container.plugin-news_home_feature')) works for elements that have at least those two classes, which is why it's picking up the second div too. To get only the div with exactly those two classes, you have a couple solid options:
Option 1: Exact attribute match
Use jQuery's attribute selector to match the full value of the class attribute. This is strict—only elements where the class string is exactly "plugin-container plugin-news_home_feature" will be selected:
$('div[class="plugin-container plugin-news_home_feature"]')
⚠️ Note: This depends on the class order being exactly the same. If the classes ever get reordered (e.g., "plugin-news_home_feature plugin-container"), this selector won't work.
Option 2: Filter out elements with extra classes
A more flexible approach is to start with your original selector, then filter out any elements that have additional classes. You can check the number of classes, or explicitly exclude the extra class from the second div:
Check class count:
$('div.plugin-container.plugin-news_home_feature').filter(function() { // Only keep elements with exactly 2 classes return this.classList.length === 2; });
Exclude the extra class:
If you know the second div has plugin-section-wrapper, you can directly exclude elements that have that class:
$('div.plugin-container.plugin-news_home_feature:not(.plugin-section-wrapper)')
This is great because it doesn't rely on class order or exact class count—any div with the first two classes but not the third will be selected.
Target the second div (all three classes)
This one's straightforward! Since the second div has all three classes, you can just chain all three class selectors together. This will only match elements that have all three classes, so the first div won't be included:
$('div.plugin-container.plugin-news_home_feature.plugin-section-wrapper')
Why your original code was selecting both divs
Just to clarify: When you use multiple class selectors like .class1.class2, jQuery matches any element that has both classes, regardless of how many other classes it has. The second div has both plugin-container and plugin-news_home_feature, so it gets picked up along with the first one. The fixes above narrow it down to only the element you want.
内容的提问来源于stack exchange,提问作者OverKast

