I have 2 divs in my page, each div have class a , b. I also have 2 urls
Goal : I want to hide div
with class b
when I'm at site/a and vice of versa.
The goal is to hide them completely from the DOM. I'm not sure how to do that.
I've tried
JS
var lastSegment = location.pathname.split('/').pop();
if (lastSegment === 'a') {
$(".a").removeClass("hidden");
} else {
$(".b").removeClass("hidden");
}
CSS
.hidden {
display: none!important;
visibility: hidden!important;
}
HTML
<div class="a hidden"> // Logic </div>
<div class="b hidden"> // Logic </div>
Result
I can see both of the div when I do inspect element.
Any helps / hints / suggestions on this will be much appreciated
jQuery's .detach() is doing this.
The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.
Here:
var lastSegment = location.pathname.split('/').pop();
if (lastSegment === 'a') {
$(".b").remove();
} else {
$(".a").remove();
}
You can use remove() function to remove it completely.
You cannot get rid on the DOM by adding and removing classes. There are multiple ways you can tackle this .
Add/Remove divs using Javascript completely. Don't render both.
if(lastSegment === "a") { $(".target").append('<div class="a">Link A</div>'); } else { $(".target").append('<div class="a">Link B</div>'); }
Use Shadow DOM - ShadowDom elements are not visible with inspect element, unless making some settings buried deep inside setting icons.
Tutorial : http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/ Thanks
you can try this
if (lastSegment === 'a') {
$(".a").removeClass("hidden");
$(".b").addClass("hidden");
} else {
$(".a").addClass("hidden");
$(".b").removeClass("hidden");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.