0

How could I hide divs that begin with id "news" but also contain a number like "news1" "news2" etc if the URL hash doesnt contain "news".

like hide if someurl.com/#events. but show any "news" div if someurl.com/news1

need in regular JS

thanks,

1
  • "someurl.com/news1".split('/')[1].indexOf('news') === 0 Commented Jun 15, 2017 at 15:32

5 Answers 5

1

Try This:-

$(function(){
  var url = window.location.hash;
 
  if(url.indexOf('news') > -1){
    $("div[id^='news']").hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="news1">News1</div><br>

<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>

Update: (Using Pure JavaScript)

(function() {
   var url = window.location.hash;
  /* for testing set the hash to 'news' */
    url='news';

 if(url.indexOf('news') > -1){
 
  var bodyDOM = document.body;
  bodyDOM.querySelectorAll("[id^='news']").forEach(function(item, index){
    item.style.display='none';
  });
 }
})();
<div id="news1">News1</div><br>

<div id="news2">news2</div><br>
<div id="news3">news3</div><br>
<div id="event">event</div><br>

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, is there a way to do this w/o JQuery. i just realized Id need to do it in plain js
@user718229, I have updated my answer. please take a look. For a visual representation, I have set the URL hash to 'news' please remove it while using the code
1

The script hasn't been tested. It does these steps:

  1. Looking for the word "#news" in URL. In our case, if there aren't any word.
  2. For each div with the ID "new" or similar
  3. Add a CSS to this div to hide it.

    <script type="text/javascript">
    $(document).ready(function () {
        if(window.location.href.indexOf("#news") < 0) {
            $("div[id^='news']").css('display', 'none');
        }
    });
    </script>
    

Comments

0

If you put a class on all the divs you'd want this apply to, you can do this:

$(document).ready(function() {
    $('.CLASSNAME').each(function(i) {
        if($(this).val().indexOf('WORD_YOURE_LOOKING_FOR') > -1) {
            $(this).css('display', 'none');
         }
    );
});

Comments

0

Well you can access the hash in a URL like so:

var hash = window.location.hash;

I'm not 100% clear what you want to do at that point. If you wanted to show the news1 div, you'd do this:

if(hash == 'news1') {
   $('#news1').show();
}

Comments

0

Try this:

var hash = window.location.hash;
$('[id^="'+hash+'"').hide();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.