简体   繁体   中英

Changing HTML using javascript without using selectors

Ok - first of all I know this isn't ideal - however we have inherited a problem and some badly thought out SSI html.

So some background: We have implemented a responsive site which has to include some SSI code from the client for global top nav and footer - so far so good. However the SSI needs to change from DESKTOP to MOBILE as the site is resized/loaded on a mobile device. We do all this client side at the moment. We have a trigger at break points to alter the dom to do all the responsive stuff.

A similar example is here http://www.conrandesigngroup.com . (Resize the browser to see what happens.)

Normally we would load the SSI into holding pages and AJAX the code in to the appropriate place using some kind of selector.

The problem: The SSI is not fully formed HTML, it looks something like this:

<!-- desktop ssi -->
</head>
<body>
Whole bunch of desktop html...
<div class="content">

Then the SSI we have for the mobile site is:

<!-- mobile ssi -->
<script>some script...</script>
</head>
<body>
Whole bunch of mobile html...
<div class="content">

So you will notice there is a closing </head> and an opening <body> and at the end there is an opening <div> . So there is no way we can select this and replace using the DOM. We were thinking of using comments either side of the code and using a javascript regex to replace the code. Im not sure if this would actually update the browser.

So in desktop mode the whole page will look like this:

<html>
<title>my page</title>
<head>
...all the head stuff
<!-- START of ssi -->
<!-- desktop ssi -->
</head>
<body>
Whole bunch of desktop html...
<div class="content">
<!-- END of SSI -->
...all the page HTML
</div>
</body>
</html>

So thats fine - the HTML is all put together serverside and we can open and close the tags correctly. The problem is how would we change the HTML INSIDE the comments using client side code <!- START of ssi -->...<!-- END of SSI -->

In the end its not really a SSI question - rather a way to change a bit of HTML which is not wrapped up nicely in an element.

Anyone come across this issue before or have any suggestions?

The common denominator is this:

  • The body element contains the content
  • Both the mobile and desktop content start with the first child of the body

The code to empty the first element would be the same for both versions:

document.getElementsByTagName("body")[0].firstChild.innerHTML = "";

Wrap the code in a pre element to make it easy to modify.

References

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM