isotropic-2022
Share
Blog
Search
Menu

Hide Elements Based On URL Text

By James LePage
 on November 17, 2020
Last modified on January 6th, 2022

Hide Elements Based On URL Text

By James LePage
 on November 17, 2020
Last modified on January 6th, 2022

In this article we wanted to talk about how to hide individual HTML elements based off of text in the URL. This is helpful if you want to selectively disable elements of your web page by using a URL parameter like so:

https://example.com/?dontshowheader

We're going to do this in complete vanilla JavaScript, meaning that it should work with pretty much anything. Browser support is 100% for anything that runs JavaScript because of this. Once you have this snippet in your memory, it can be fairly helpful for iframe embeds, and more.

For us, we use this to hide our header and footer when adding content to a page via an iframe.

<script> if (/URLSTRING/.test(window.location.href)) { document.getElementById('ELEMENTTOHIDE').style.display = 'none';} </script>
Code language: HTML, XML (xml)

To get this working on your website, all you need to do is replace 2 things in this code snippet and then install it underneath the element that you want to hide.

The first thing is the text contained in the URL. If the URL contains the text in that snippet, then the element that it refers to will be hidden. If the URL does not contain the text, then nothing will happen.

In the example, we have “URLSTRING” (so if a url looked like this, https://example.com/?urlstring, and element would be hidden).

The next thing is the element you want to hide. This is selected by the element ID. Just replace “ELEMENTTOHIDE” with the ID of the element that you need to hide.

We use a URL parameter to selectively show and hide based off text in the URL because it makes no difference to the overall page, doesn't bring you to another subdirectory, and works off the bat.

Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Monika
Monika
3 months ago

Does not work for me. Do you have an example page for me? Regards, Monika

Article By
James LePage
Contributors/Editors
notloggedin
James LePage is the founder of Isotropic Design, a digital agency that builds WordPress websites. I read, write and design constantly!
We're looking for new authors. Explore Isotropic Jobs.
Close
🇺🇸 English
Save posts, access exclusive content, join members-only communities and more.
Dark Mode Toggle
Love web dev? Join the Isotropic weekly newsletter.
cross
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
0

Your Cart is Empty