简体   繁体   中英

Some way to wrap any html element with another element?

The message is submited via form. It can contain html as well as normal text .

ie:

Why this code doesn't work for me?

<script type="text/javascript">
    var _gaq = _gaq || [];

    _gaq.push(['_setAccount', 'UA-XXXXX-X']);

    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

I would like to surround html element with pre tag.

ie

Why this code doesn't work for me?

<pre>
    <script type="text/javascript">
        var _gaq = _gaq || [];

        _gaq.push(['_setAccount', 'UA-XXXXX-X']);

        _gaq.push(['_trackPageview']);

        (function() {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
    </script>
</pre>

I asked earlier about it in php chat room and author of the answer in this question suggested to read the solution: php DOMDocument: complete transform of form element? wrapping and removing?

Everything is perfect in this example exept few things. I need to wrap any html element obviously exept pre itself.

  1. If elements are folded, then wrap only outer element.
  2. If they are separate, then wrap each of them.
  3. If there is only open tag, then wrap it only(no need of fixing with close tag).

Does anyone have any possible idea for a solution to this question? Thanks in advance to all who can help.

I am not sure how well DOMDocument handles HTML that is not well formed. And if the message contains closing tags without opening tags you will probably get errors. But I think you will get the idea from the following...

Wrap the whole message into eg a div to make it parseable. Then load the string into a DOMDocument. Use DOMXPath like in the linked answer to find the top most elements inside the div you created and wrap those with pre :

$dom = new DOMDocument();
$dom->loadHTML("<div>$msg</div>");

$xpath = new DOMXPath($dom);
$query = $xpath->query("body/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