<p>You could use the <a href="https://twig.sensiolabs.org/doc/2.x/templates.html#containment-operator" rel="nofollow noreferrer"><code>in</code> operator</a> to search for a substring in your markup.</p>

<pre><code>{% set imageExists = '&lt;img' in entry.body.getRawContent() %}
{% set classAttr = imageExists ? 'with-image' : '' %}

&lt;div class="{{ classAttr }}"&gt;
    {{ entry.body }}
&lt;/div&gt;
</code></pre>

<p>Another, probably bit more reliable way to test for <code>&lt;img&gt;</code> elements is to use the <a href="https://github.com/mmikkel/RetconHTML-Craft" rel="nofollow noreferrer">Retcon</a> plugin, which uses DOMdocument to parse the markup.</p>

<p>A combination of <code>retconOnly</code> and <code>length</code> filters should get you there.</p>

<pre><code>{% set imageExists = entry.body|retconOnly('img')|length %}
</code></pre>

CC BY-SA 3.0
2017-04-28T10:09:10.720Z
Thank you...  my code is now like this and works.                              {% set imageExists = block.textArea|retconOnly('img')|length %}
                            {% set classAttr = imageExists ? 'with-image' : '' %}
                            <div class="entryTxt {{ classAttr }}">
                                {{ block.textArea|retconUnwrap('img') }}
                            </div>
Martin
CC BY-SA 3.0
2017-04-28T09:58:57.123Z
2017-04-28T10:06:03.407Z
2017-04-28T10:06:03.407Z
carlcs
<p>I have a DIV wrapping a Rich Text field.  I would like to add a class name to the DIV only if an image is present in the text field.  Is there a way to check for an image?</p>

<richtext>
Check for an image in Rich Text Field
# Check for an image in Rich Text Field

(Asked by: username_0 on 2017-04-28)

I have a DIV wrapping a Rich Text field. I would like to add a class name to the DIV only if an image is present in the text field. Is there a way to check for an image?

**Tags:** richtext


---

## 1 answers

### Answer by username_1 on 2017-04-28. Score: 3 | Accepted answer

You could use the in operator to search for a substring in your markup.
{% set imageExists = '
    {{ entry.body }}


Another, probably bit more reliable way to test for  elements is to use the Retcon plugin, which uses DOMdocument to parse the markup.
A combination of retconOnly and length filters should get you there.
{% set imageExists = entry.body|retconOnly('img')|length %}

> **Comments:**
> **username_0**: Thank you...  my code is now like this and works.                              {% set imageExists = block.textArea|retconOnly('img')|length %}                             {% set classAttr = imageExists ? 'with-image' : '' %}                             <div class="entryTxt {{ classAttr }}">                                 {{ block.textArea|retconUnwrap('img') }}                             </div>  

---

