Hide div if URL contains word

I need to hide the div if the page URL contains a specific word. Thanks to this site, I was able to successfully find if the URL contains the word. This code works:

<script type="text/javascript"> if (window.location.href.indexOf("Bar-Ends") != -1) { alert("your url contains bar ends"); } </script> 

but for some reason this will not work to hide the div, for example:

 <script type="text/javascript"> if (window.location.href.indexOf("Bar-Ends") != -1) { $("#notBarEnds").hide(); } </script> <div id="notBarEnds">this is not bar ends</div> 

Does anyone know what is wrong with this code? Any help is appreciated Thanks

+4
source share
4 answers

Pay attention to the order:

 <div id="notBarEnds">this is not bar ends</div> <script type="text/javascript"> if (window.location.href.indexOf("Bar-Ends") != -1) { $("#notBarEnds").hide(); } </script> 

or

 <script type="text/javascript"> $(document).ready(function () { if (window.location.href.indexOf("Bar-Ends") != -1) { $("#notBarEnds").hide(); } } </script> 

Waiting for the completion of the entire document

+11
source

Try:

 $(document).ready(function () { if (window.location.href.indexOf("Bar-Ends") != -1) { $("#notBarEnds").hide(); } }); 

Your div is not yet loaded when the script is running.

+2
source

You run the built-in script as you build the HTML, while the script is running, there is no div named #notBarEnds , you need to run it as a function after the document is loaded.

0
source

I write it without checking it if regex: D change does not work

 $(document).on('ready', function() { if(window.location.href.match(/Bar\-Ends/i)) $("#notBarEnds").hide(); }); 
0
source

All Articles