HTML Rewriter : If element contains text - do something with attributes

Please share an example with HTMLRewriter - if element contains text,

for example <a> or <p>

then do something with attributes.

Thanks in advance!

The forum is not strictly for custom JavaScript development.

What have you tried so far and why didnt it work?

As example - I need to put a text into attribute

<a href="#">red</a> => <a href="#" data-color="red">red</a>

I separately access a text inside tag using HTMLRewriter.text and element properties using HTMLRewriter.element - but I’ve no idea how to combine them. If it is possible to access text for element - there will be no problem.

Post the code you have tried so far.

I write nothing becasue element(element) can’t access “innertext” property and I’ve no idea how to pass variable from text(text) to element(element) in HTMLRewriter.

Here is my task in non-theoretical task.

I need to delete all elements containing “yastatic” text in text, src of href. Here is code

const yastaticrewriter = new HTMLRewriter()
.on('link[href*="yastatic"]', new YaStaticRewriter())
.on('script', new YaStaticRewriter('element')); 
 html = yastaticrewriter.transform(html);


class YaStaticRewriter

    const href = element.getAttribute('href');
    const src = element.getAttribute('src');

    if ((href !== null && href.includes('yastatic')) || (src !== null && src.includes('yastatic'))) {

text(element) {
    if (element.text !== null && element.text.includes('yashare')) {


I expect all script tags containing “yashare” in text to be removed

var yashareInstance1 = new Ya.share({
element: “yashare1”,

		l10n: "default",
		theme: "default",
		elementStyle: {
			type: "button",  quickServices: ['facebook', 'gplus', 'twitter', 'vkontakte']
		popupStyle: {copyPasteField:true,
			blocks: {'': ['blogger', 'evernote', 'linkedin', 'lj', 'moikrug', 'moimir', 'myspace', 'odnoklassniki', 'surfingbird']}



but get

     <script type="text/javascript"> 


as result (all content in tags is removed, but tags still exist)

From what I understand you cannot access the text content of an element via the element reference. Equally, you cannot access the surrounding element when receiving a text element.

If Cloudflare supported pseudo classes you could do something along the lines of script:contains("yashare") but that doesnt seem to be supported either.

In short, I somewhat doubt your use case is possible with HTMLRewriter and you might have to go the traditional route of string parsing.