Question:
<div id="foo">...<div>
<div id="foo-bar">...<div>
<div id="foo-1">...<div>
<div id="foo-2">...<div>
Is there a selector that matches only the element whose id
attribute is foo-{数値}
for HTML like the above?
At the moment, all the elements acquired by [id^=foo]
are additionally filtered and moved, but if possible, I would like to complete it with only the CSS selector.
$("[id^=foo]").each(function() {
if (!this.id.match(/^foo-\d+/)) return;
...
});
Answer: Answer:
There is none.
http://www.w3.org/TR/css3-selectors/#attribute-selectors can only specify identifier
or string
in the val
part such as attr^=val
= must be ).
Attribute values must be CSS identifiers or strings .
And neither identifier
nor string
defines a notation with wildcards or regular expressions. Therefore, such a match cannot be achieved with pure CSS selectors alone.
However, jQuery will use CSS selectors implemented by Sizzle, so you could use the extended API to define such selectors yourself.
PS: I was curious, so I tried jQuery's custom selector. As a result, I was able to define and extend the jQuery selector myself by adding code like the following.
jQuery.extend(jQuery.expr[":"], {
"id-foo-num": function (el) {
return el.id.match(/^foo-\d+/);
}
});
When using it, use pseudo selector like jQuery(":id-foo-num")
.
var output = jQuery('#output');
jQuery.extend(jQuery.expr[":"], {
"id-foo-num": function(el) {
return el.id.match(/^foo-\d+/);
}
});
jQuery(":id-foo-num").each(function() {
output.append(jQuery("<span>" + this.id + ":" + this.innerText + "</span><br />"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div id="foo">NG</div>
<div id="foo-bar">NG</div>
<div id="foo-1">OK</div>
<div id="foo-23">OK</div>
<div id="foo-999">OK</div>
</div>
<hr />
<div id="output">
</div>