snipt

Ctrl+h for KB shortcuts

JavaScript

jquery if exists DOM element

1
2
3
4
5
if ( $('#myDiv').length ) {

  //do something

}
https://snipt.net/embed/cf1dbea1e1b6f0baa01c2301f1824d97/
/raw/cf1dbea1e1b6f0baa01c2301f1824d97/
cf1dbea1e1b6f0baa01c2301f1824d97
js
JavaScript
5
2019-07-23T11:38:11
True
False
False
/api/public/snipt/33933/
jquery-if-exists-dom-element
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="k">if</span> <span class="p">(</span> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#myDiv&#39;</span><span class="p">).</span><span class="nx">length</span> <span class="p">)</span> <span class="p">{</span> </span><span id="L-2"><a name="L-2"></a> </span><span id="L-3"><a name="L-3"></a> <span class="c1">//do something</span> </span><span id="L-4"><a name="L-4"></a> </span><span id="L-5"><a name="L-5"></a><span class="p">}</span> </span></pre></div> </td></tr></table>
dom, jquery