1

I have code similar to this:

<div>
<div> randomText 11235 </div>
<div> randomText </div>
<div> randomText </div>
<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

1
  • If you have control over the html generated, you are better off adding a 'class=HasData' attribute to the div. Then you can use jQuery class selector instead of parsing a bunch of text. Commented Sep 5, 2011 at 2:25

2 Answers 2

9

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,"");
});
Sign up to request clarification or add additional context in comments.

Comments

1

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/

1 Comment

You're missing out on part of the benefit of passing a function to .html(). That is that you don't need to create a jQuery object and call .html() to get the current content. Just use the second parameter to the function you passed. jsfiddle.net/DeybW/1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.