search

Home  >  Q&A  >  body text

How to use JavaScript to redirect a page if a specific div class does not exist?

<p>I am trying to create a redirect if a specific div class does not exist in the HTML code of the page<strong>. </strong></p> <p> So far I've written the following code, but I guess now it's the "opposite way" (redirect if the div exists, not if it doesn't): </p> <pre class="brush:php;toolbar:false;">if (!document.getElementsByClassName("flickity-lazyloaded")[0]) { window.location.href = "/404";}</pre> <p>How do I make it work the way I want? </p> <p>FYI: The weird thing is that when I create a JSFiddle it works as expected - but on an actual website it redirects me despite the presence of the ".flickity-lazyloaded" class in the HTML: < ;/p> <p>https://jsfiddle.net/v97k5new/1/</p>
P粉821274260P粉821274260500 days ago516

reply all(1)I'll reply

  • P粉613735289

    P粉6137352892023-08-16 00:36:50


    if (!document.getElementsByClassName("flickity-lazyloaded")[0]) {
    window.location.href = "https://stackoverflow.com"}
    <div> hello </div>

    reply
    0
  • Cancelreply