开发者

Manipulate DOM element to extract some nodes and remove others

I need to manipulate HTML code. Specifically, the user should be able to copy/paste the code to create an AddThis button in a textarea, and I want to manipulate the pasted code.

A typical AddThis button looks like this :

<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox add开发者_StackOverflow社区this_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-123456798"></script>
<!-- AddThis Button END -->

It consists of start and end comments, a div and/or some links, followed by 2 scripts: a config setting, and a call to their library.

The problem is, we need to call this many times on the page ; so, if I just put this every time I want to place an AddThis button, I fear that at least some browsers will have weird behavior, if it works at all.

So, I want to extract the config setting and the lib call, so I can call them just once, and extract the buttons config, so I can place it as many times as I want on the page.

I have already done that :

    var codeAT = $(this).val();
    if (codeAT.indexOf("AddThis Button BEGIN") >= 0) {
        codeAT = codeAT.replace("&lt;", "<");
        codeAT = codeAT.replace("&gt;", ">");

        codeAT = $(codeAT);

        // extract the call to the config var and the lib
        var scriptConfig = "";
        var scriptSRC = "";
        codeAT.each(function() {
            if ($(this).attr("nodeName") == "SCRIPT") {
                if ($(this).attr("src") && $(this).attr("src") != "") {
                    scriptSRC = $(this).attr("src");
                } else {
                    scriptConfig = $(this).text();
                }
            }
        });

        // extract the addthis identifier
        scriptSRC = scriptSRC.split("=")[1];
    }

Now, I can use the vars scriptConfig (with var addthis_config = {"data_track_clickback":true};) and scriptSRC (with ra-123456789), and they have the correct values.

What I want now, is the original code (between the two comments), without the comments, and without the script tags.

To remove the tags, I tried to use codeAT.remove($(this)), but it crashes (something about c.replace not being a function).

To get the code back, I tried codeAT.html(), but it gets only the tags.


Instead of .each() I'd do:

//remove <script> tags and get required info
var scriptSRC = $('script[src]', codeAT).remove().attr('src');
var scriptConfig = $('script:not([src])', codeAT).remove().text();

//get the code (as string)
var code = $('<div>').append(codeAT).remove().html();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜