Is it possible to select css generated content? [duplicate]

一个人想着一个人 提交于 2019-12-03 09:25:13

No, you can't.

See Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery. To repeat what is described there, generated content is not part of the DOM.

In the words of the CSS2.1 spec,

Generated content does not alter the document tree.

Generated content only exists in the visual world of the rendering engine. Selecting is about selecting portions of the DOM. Generated content is not in the DOM, hence cannot be selected. For the same reason, generated counters or list item bullets cannot be selected.

Mr7-itsurdeveloper

Do not store content that should be visible and accessible in data attributes, because assistive technology may not access them

Check These links :

http://www.karlgroves.com/2013/08/26/css-generated-content-is-not-content/ https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Danield

Instead of actually selecting the generated content, you could simulate this with some javascript.

I stumbled over this David Walsh blog, where he provides code that fetches generated content.

Using that, you can append the generated content to the regular content to simulate selection of the generated content, then you can set the generated content with display:none so that it doesn't appear twice. Like this:

FIDDLE

String.prototype.unquoted = function() {
  return this.replace(/(^['"])|(['"]$)/g, '')
}

var element = document.getElementById('div1');

var content = window.getComputedStyle(
  element, ':after'
).getPropertyValue('content');

element.innerHTML = element.innerHTML + content.unquoted();

console.log(content.unquoted());
div:after {
  content: attr(data-generated);
  display: none;
}
<div id="div1" data-generated=" world!">Hello</div>

So why would you ever want to do something like that?

Well, you'd probably never want to do this, but I left a long comment on the question explaining a particular constraint that I once had, where this could have been a solution.

NB: I do realize that this 'solution' doesn't really select the generated content itself, but decided to post this answer in case somebody out there ever needed a workaround.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!