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
3.6k views
in Technique[技术] by (71.8m points)

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 after data-d- gets randomized by the site).

<div data-d-9y3x>
<div data-d-m01>
<div data-d-whatever>

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

1 Reply

0 votes
by (71.8m points)

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;
    }
  }
}
<div data-d-9y3x>Some</div>
<div data-d-m01>text</div>
<div data-d-whatever>content</div>
<div test-data-d-whatever>and</div>
<div d-whatever>more</div>
<div testdata-d-whatever>...</div>

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

...