Change color of specific text within HTML tags using Javascript

前端 未结 1 1196
粉色の甜心
粉色の甜心 2021-01-22 08:11

The question says it all. For example I have the following HTML code:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiu

1条回答
  •  隐瞒了意图╮
    2021-01-22 08:40

    You can't do it without modifying the contents of the span. So you either do that in the source, or you do it later by manipulating the DOM (in your case, via jQuery).

    So for instance:

    var span = $("#span");
    span.html(span.html().replace(/dolor/, '$&'));
    
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor

    The $& in the replacement string is the word that was found. In the above, only the first occurrence would be replaced; to replace multiple occurrences, add a g to the end of the regular expression (/dolor/g).

    Note that if you have any event handlers attached to any elements within the span, they will get removed by this, as the contents of the span get removed and then replaced. (As your example doesn't have any elements at all within the span, I figured that wouldn't be the case, but figured I should mention it.)

    0 讨论(0)
提交回复
热议问题