1

Is it possible to address specific text within an element with CSS? E.g. :

<div class="myClass">Good content --bad content--</div>

I'd like to hide the text between -- and the two delimiters (--[...]--) as well. So after all it should look like this:

<div class="myClass">Good content </div>

I CANNOT place the bad content within some HTML tags (technical restrictions)!

Maor Bachar
  • 81
  • 1
  • 8
alve89
  • 971
  • 1
  • 9
  • 31
  • 2
    it is possible with `jQuery` but I have never heard of such thing in CSS – Manish Yadav Jun 17 '17 at 11:55
  • 3
    No, not with CSS - you'll need JS for that – Johannes Jun 17 '17 at 11:56
  • Are both [text content] necessarily baked into the DOM? Acknowledging that you cannot tag the delimited content; can you affect the HTML at all? – Ito Pizarro Jun 17 '17 at 12:07
  • 1
    Possible duplicate of [Is there a CSS selector for elements containing certain text?](https://stackoverflow.com/questions/1520429/is-there-a-css-selector-for-elements-containing-certain-text) – I haz kode Jun 17 '17 at 12:44

4 Answers4

2

If your problem is to only hide specific text for people without js enabled and you have access to source and can modify js/html/css then you could try to save your unsafe text in attribute and assign it by default with pseudo selector and on load of body within a script assign a class that will rewrite the pseudo selector contents:

.myClass::after {
  content: attr(data-no-js);
}

.js-enabled .myClass::after {
  content: "";
}
<script>document.body.classList.add('js-enabled');</script>
<div class="myClass" data-no-js=" --bad content--">Good content</div>
Karen Grigoryan
  • 5,234
  • 2
  • 21
  • 35
2

Is it possible to address specific text within an element with CSS?

No, it's not.

1

You can't really select based on content as per the specs.

But, here's something - experimental - just for fun since you said CSS only which I don't think is possible.

This has no cross browser support yet...and by I mean it won't work on IE or Edge. I tested it in Chrome 58 and FF 54 and all is good there.

With that being said, Can I use says this will work for at least 89% of users.

.myClass {
  -webkit-mask-image: -webkit-linear-gradient(left, rgba(0, 0, 0, 1)14%, /** <---- Use this percentage to determine the cutoff point **/
  rgba(0, 0, 0, 0)0, rgba(0, 0, 0, 0));
}
<div class="myClass">Good content --bad content--</div>
I haz kode
  • 1,587
  • 3
  • 19
  • 39
0

You have to use Javascript, you can use String replace() method :

var str = 'Good content --bad content-- sometext';
str = str.replace(/--[^]*--/g, "");
alert(str); /* Good content sometext */

If you really don't want to use JavaScript, here's a CSS solution, but you have to adapt it to your font-size, I'm don't think it's the best approach though.

.myClass{width:100px; height: 20px; overflow:hidden;}
<div class="myClass">Good content --bad content--</div>
Horai Nuri
  • 5,358
  • 16
  • 75
  • 127