Reputation: 95
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.
Upvotes: 0
Views: 101
Reputation: 2833
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.
Upvotes: 2
Reputation: 6628
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();
}
});
Upvotes: 0