jQuery find and replace string

前端 未结 6 954
天命终不由人
天命终不由人 2020-11-28 22:37

I have somewhere on website a specific text, let\'s say \"lollypops\", and I want to replace all the occurrences of this string with \"marshmellows\". The problem is that I

6条回答
  •  温柔的废话
    2020-11-28 23:17

    You could do something this way:

    $(document.body).find('*').each(function() {
        if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
            $(this).removeClass('lollypops');
            $(this).addClass('marshmellows');
        }
        var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
        var text = $(this).text(); //getting just current node text
        text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
        $(this).text(text); //setting text
        $(this).append(tmp); //re-append 'foundlings'
    });
    

    example: http://jsfiddle.net/steweb/MhQZD/

提交回复
热议问题