The issue is simply as following, when I try to select a class that starts with a keyword , and ends with another keyword, this works fine, if and only if the element has a single class, if element has multiple classes, the selector will return an empty collection.
Here is code to explain the issue
// try removing custom-class from first element --> returns 2 alert($("div[class^='start'][class*='end']").length) // will return 1 by default , only 1 element has single class.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="custom-class start-mid-end" data-custom="1st Div"> </div> <div class="start-mid-end" data-custom="2nd Div"> </div>
That's because for the element with class="custom-class start-mid-end"
, the value of its class
attribute begins with custom
, not start
. Remember, the attribute selectors operate on the attribute value as a single string; they don't care that the class
attribute is "special" in HTML.
Regarding a solution to your problem: there aren't any without caveats. As the most practical workaround, I would suggest using multiple classes instead of just one. For example, instead of just prefix-X-suffix
also add the classes prefix- -suffix
and then you can select your elements simply with
$("div[.prefix-.-suffix]")
Another option would be to use filter
to customize the class selection logic, eg
$("div").filter(function() { return /\bstart\S*end\b/.test(this.className); })
The regex \\bstart\\S*end\\b
matches any sequence of non-whitespace characters with the prefix start
and the suffix end
, which is what you are after.
您使用的选择器引用了整个属性字符串,因此class="start what ever end"
将是一个匹配项。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.