简体   繁体   中英

JavaScript - wrap contents within a DIV, if a condition is met

I have a fairly complicated problem.

The usual markup (no problems here):

   <div class="wrapper">
    <div class="title"> bla bla... </div>
    <div class="content"> ...content... </div>
   </div>

The "twisted" markup:

   <div class="wrapper">
       ...content... </div>
   </div>

As you can see the opening tag for div.content is missing. Unfortunately I have no control over the output within .wrapper :(

So, my question is: how can I detect if div.title is present, and if not - insert <div class="content"> (not the .title) after div.wrapper ?

I'm aware how to do this with jQuery, but I need a pure javascript solution because with jQuery you get a small "delay" before the layout gets fixed. Any ideas?

There is a fair bit more code without jQuery.

var divs = document.getElementsByTagName('div'),
    foundTitleDiv = false;

for (var i = 0, divsLength = divs.length; i < divsLength; i++) {
    if (divs[i].className.match(/\btitle\b/)) {
        foundTitleDiv = true;
        break;
    }
}

if (foundTitleDiv) {
    var wrapper = document.createElement('div'); 
    wrapper.className = 'content';
    var div = divs[i]; 
    wrapper.appendChild(div.cloneNode(true));
    div.parentNode.replaceChild(wrapper, div);
}

It works!

Place this at the bottom of your script, or you can wait for the entire window loaded with window.onload = function() { } or research onDOMReady events.

Whilst this answers your question, the fact you have invalid HTML (the extraneous </div> ) may make this solution invalid.

Well, JQuery is pure Javascript, but with JQuery there's a lot more Javascript for the browser to parse, that might be why you are experiencing some delay. I don't know exactly how you would go about fixing this with Javascript, because you are outputting invalid HTML. which will be interpretted differently by different browsers. The correct thing to do would be to output proper HTML by the use of server side code such as PHP, or ASP.

Perhaps you can fix it on the server before sending it by searching for and, if it is missing, add it. If you can't fix it on the server, then you can do it with inline javascript, but you will need to add the content as a javascript variable, parse it, then write it out.

Here's an example (FYI, I know the RegEx is wrong, but figured it got the point across ok).

<div class="wrapper">
    <div class="title"> bla bla... </div>
    <script type="text\javascript">
        var content = "<div class="content"> ...content..." 
        if (!content.match(/<div class="content">/))
            content = "<div class="content">" + content;
        document.Write(content)
    </script>
    </div>
</div>

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