Julia Davies
Julia Davies

Reputation: 7

Change body by if else statement - url

If url is subdomain http://one.example.com/dsnknw?211218 then show div one, if http://two.example.com/ppppnw?201218 than show div two.

Each body has background image

<style>
#siteone {
background: url(http://example.info/backgroundone.PNG); 
    background-repeat: no-repeat;
    background-size:cover;
    }
#sitetwo {
    background: url(http://example.info/backgroundtwo.PNG); 
    background-repeat: no-repeat;
    background-size:cover;
    }
</style>

and a link associated:

<div id="one">
<a id="link1" href="https://click.com" target="_top"></a>
</div>

<div id="two">
<a id="link2" href="https://click2.com" target="_top"></a>
</div>

I have tried a few codes including

document.getElementById("body")

Class of ID Change based on URL - URL Based Image Swap - Creating Conditional Statement Based On Page URL ETC

Upvotes: 0

Views: 434

Answers (1)

Abana Clara
Abana Clara

Reputation: 4650

Based on Juan's comment, two body tags isn't a viable approach for this. https://developer.mozilla.org/en-US/docs/Web/HTML/Element#Sectioning_root. You should make use of parent wrappers instead.

<div class="parent">
<a id="link2" href="https://click.com" target="_top"></a>
</div>

Using window.location will help you parse the current URL so you can properly do what you need.

What I would do is query the element that has href attribute of window.location.href and then get the .parentElement to get the direct parent.

const url = window.location.href;
const targetParent = document.querySelector('.parent a[href="' + url + '"]').parentElement;

targetBody.style.display = "block";

This will not work if <a> is located somewhere deeper. That being the case I would say add another attribute for the parent so we can directly query it.

<div class="parent" url="https://click.com">
<a id="link2" href="https://click.com" target="_top"></a>
</div>

then

const url = window.location.href;
const targetParent = document.querySelector('.parent[url="' + url + '"]').parentElement;

If your url has other extra strings like http://click.com?id=foobar then this will also not work. You would have to manually concatenate other properties from window.location so you can only get what you need.

const baseDomainWithSubPath = window.location.origin + "/" + window.location.pathname;
const baseDomain = window.location.origin;
const subDomain = window.location.pathname;

Upvotes: 1

Related Questions