开发者

Target <div> with Javascript?

I have code similar to this:

<div>
<div> randomText 11235 </div>
<div> randomText </div>
<div> randomText </div>开发者_JAVA百科
<div> randomText </div>
<div> randomText </div>
</div>

As you can see, each div contains random text but the first div also has a "11235" added at the end.

This "11235" will be added at the end of any of the divs (Note that this can be multiple divs).

Here is one scenario that can happen:

<div>
<div> randomText </div>
<div> randomText 11235 </div>
<div> randomText </div>
<div> randomText 11235 </div>
<div> randomText </div>
</div> 

Is is possible to be able to target those divs that only have the 11235 added onto the end and remove the 11235.

I would prefer a solution in javascript (jQuery is fine).

Thanks


Using jQuery you could iterate all divs containing 11235 and replace '11235' in the text of those elements using the standard js-replace function:

$("div div:contains('11235')").each(function () {
    $(this).text($(this).text().replace("11235",""));
});

As noted by Rick you could also use implicit iteration, it's slightly more elegant:

$("div div:contains(11235)").text(function (i, text) {
     return text.replace("11235","");
});

If there's any chance each div element might contain multiple occurances of 11235 use the regex-version of replace:

$("div div:contains(11235)").text(function (i, text) {
    return text.replace(/11235/g,"");
});


You can use the :contains() selector and the html() method of jQuery, like this:

$("div:contains(11235)").html(function( i, html ) {
   return $.trim( ( html || "" ).replace(/11235/g, "") );
});

This works without the need for iterating with each() as jQuery is built on the contept of "implied iteration", meaning all setter methods will automatically iterate each element they receive from the calling jQuery object (unless otherwise noted).

See: http://jsfiddle.net/rwaldron/DeybW/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜