0

What I want is to hide certain element using Javascript. Specifically, I want this element showed only if the URL contains the text 'cli'. I tried that using next code

    var regex = window.location.href;
if(regex.indexOf('cli')>-1){
$(window).load(function() {
    $("[routerlinkactive]")[1].remove();
});
}

The routerlnkactive parts works separatedly. That is, if no if statement is written, it is always removed. But I want that to work only with that URL. How could I do that?

Doesn't seem to be working neither with xxx.html or with xxx.html?cli=30

Thank you.

2 Answers 2

2

try using the indexOf() function. So something like

 var regex = window.location.href;
 if(regex.indexOf('cli')>-1){ //if cli is there
        $("[routerlinkactive]")[1].hide(); //hide
  }

It will return -1 if not found, and will return the string position number if found (starting at 0).

Also, you should use .hide() to hide, not remove.

UPDATE:

since you are saying its still not working, i have just checked, and this works:

var regex = "xxxxxx.com?cli=50";
if(regex.indexOf('cli')>-1){
   alert(true);
}else{
   alert(false);
}

So replace alert() with the hide() function and make sure the html is correctly referenced (even though you said that was working okay?). And the value of regex should be window.location.href. Try adding and removing 'cli' and youll see the difference.

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

3 Comments

Doesn't seem to be working. It does the same with xxxx.html and with xxxx.html?cli=30 And I'm using remove as the hide() function of Jquery didn't seem to be working
please update your code in question and ill take a look.
For some reason, hide doesn't work not even using Web Console. But using remove works. Thank you.
0

Remove() is not the right choice, that will remove the element from the DOM.

Use hide() and show().

$(document).ready(function(){
    //Hide your element by default on page load
    $("[routerlinkactive]")[1].hide();
    if(window.location.href.indexOf("cli") > -1) {
        //If URL has "cli" then show that element.
        $("[routerlinkactive]")[1].show();
    }
});

Reference of indexOf()

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.