开发者

How do I find specific words in elements with specific classes with Javascript/jQuery?

开发者 https://www.devze.com 2023-02-09 21:34 出处:网络
I have a class for DIVs called .post and I\'d like to find words inside that element and replace them with something else. That words must also not be i开发者_开发技巧nside elements with other classes

I have a class for DIVs called .post and I'd like to find words inside that element and replace them with something else. That words must also not be i开发者_开发技巧nside elements with other classes (.tiptrig and .postheader).

I'd really like to achieve this but I don't know how... I am new to Javascript and especially jQuery.


Seems like an easy task.

$('.post').each(function() {
    $(this).html(function(index, html) {
        return html.replace(/THEWORD/g, 'something else');
    });
});

This would iterate over all nodes which own the class .post and replace the word THEWORD with something else. Be aware of that his is dangerous too because you could also modify HTML tag names for instance. So this only makes sense if you want to add/modify HTML code aswell.

demo: http://www.jsfiddle.net/XGuGy/

Probably a better idea to access the text():

$('.post').each(function() {
    var $this = $(this);

    if( !$this.closest('.postheader').length && !$this.closest('.tiptrig ').length ) {
         $this.text(function(index, text) {
            return text.replace(/you/g, 'you fool');
         });
    }
});

demo: http://www.jsfiddle.net/XGuGy/1/

0

精彩评论

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