Selecting text between comment tags with jquery

2019-07-30 05:34发布

问题:

Tried several methods to give the two Text content different class names that is between the comment blocks.

<a>
<!--:en-->Text1<!--:-->
<!--:fr-->Text2<!--:-->
</a>

The closest solution that I found is I think, Jquery Next Adjacent Selector and tried to use jQuery('prev + next') function but all the examples are targeting html elements like;

$("label + input").addClass("classone");

I just couldn't find a way to Select the text that comes after comment blocks.

回答1:

The easiest way is to use a comments plugin like this one.



回答2:

I'm not sure how fast that would be but you can make it check all the code in the body and replace those predefined classes. If you're interested in a specific tag such as <a> that might be even faster. This would be my approach.

var classes = {en:'classEN',fr:'classFR'};
// predefined class pairs
$('body').children().each(function() {
    var html = $(this).html();
    // grabs all the html code. then finds and replaces:
    html = html.replace(/<!--\s*:(\w+)(.*?)-->(.*?)<!--\s*:\s*-->/gi, function() {
        var lang = arguments[1].toLowerCase();
        // this catches the first parenthesized group that consists
        // of letters (after the colon) and converts it into lowercase
        if (!classes[lang]) return arguments[0];
        // returns the original if no match if found in the classes object
        var comment = '';
        if (!/^\s*$/.test(arguments[2])) comment = '<!--' + arguments[2] + '-->';
        // if you have a comment like <!--:en This is English-->
        // it keeps the comment as <!-- This is English --> and...
        return comment + '<span class="' + classes[lang] + '">' + arguments[3] + '</span>';
        // returns the result
    });
    $(this).html(html);
    // finally reassigns the modified result to each child
});