Css Selector To Match Elements By Attribute's Name Start
Is there any CSS selector to match these elements? (I need it for adblocker config, looked at W3C selectors document - no hints found there. Generic solution needed because part af
Solution 1:
No, there is currently no way to select elements based on the presence of an attribute whose name is starting with
a certain value. The starts with
selection is only possible for attribute values.
Such a selector is not mentioned in the CSS Selectors Level 4 spec also and so it doesn't look like it would be available anytime soon.
You have the following choices:
- Use group of selectors with all possible attribute name values in the format
element[attribute-name]
. But this option is not viable when the exact attribute names are not fixed/unknown. - Use JavaScript (or some other scripting library of your preference). Below is a very quick rough sample for the benefit of future visitors.
var el = document.getElementsByTagName('div');
for (var i = 0; i < el.length; i++) {
var attr = el[i].attributes; /* get all attributes on the element */for (var j = 0; j < attr.length; j++) {
if (attr[j].name.indexOf('data-') == 0) { /* if element has an attribute whose name has data- */
el[i].style.color = 'red';
break;
}
}
}
<divdata-d-9y3x>Some</div><divdata-d-m01>text</div><divdata-d-whatever>content</div><divtest-data-d-whatever>and</div><divd-whatever>more</div><divtestdata-d-whatever>...</div>
Solution 2:
With ES6+
you can use spread operator (...
) and then filter those element that their attribute names' start with data-d-
:
var res = [...document.querySelectorAll("*")]
.filter(t => [...t.attributes]
.filter(({ name }) => name.startsWith("data-d-")).length > 0)
console.log(res);
<divdata-d-9y3x>Some</div><divdata-d-m01>text</div><divdata-d-whatever>content</div><divtest-data-d-whatever>and</div><divd-whatever>more</div><divtestdata-d-whatever>...</div>
Post a Comment for "Css Selector To Match Elements By Attribute's Name Start"