0

Sounds simple, but I spent at least 6 hours with no luck.

For example, I have the following code

<div data-width="123">  
 <p>Hi 123</p>
 <img src="123.jpg" />
</div>

and I need to transform every 123 to 999

<div data-width="999">  
 <p>Hi 999</p>
 <img src="999.jpg" />
</div>

I've tried using several "replacing" methods, but nothing works. I just need to replace with 999 where every 123.

Thanks guys!

3 Answers 3

3

Assume you wrap using another element

<div class='test'>
    <div data-width="123">  
     <p>Hi 123</p>
     <img src="123.jpg" />
   </div>    
 </div>

You can do something like this

$('.test').html($('.test').html().replace(/123/g, '999'));

You basically take out all elements inside that element as string and do string replace and put the modified string back to the element.

See demo below

http://jsfiddle.net/petrabarus/Ph5Qz/

or you can just do this

$('body').html($('body').html().replace(/123/g, '999'));
Sign up to request clarification or add additional context in comments.

1 Comment

You rock. Your last line saved my day. Such code, many thanks, so appreciate, very happy, wow.
2

Try this... it might helps you.. Check here

HTML:

 <div class="target" data-width="123">  
 <p>Hi 123</p>
 <img src="123.jpg" alt="123.jpg" />
</div>

Script:

var target = $(".target");
    var _replaced = target[0].outerHTML.replace(RegExp("123", "ig"), "999");
    $(_replaced).insertAfter(target);
    target.remove();

Comments

1
$('div').each(function () {
if ($(this).data('width') == '123') {
    $(this).attr('data-width', '999');
    $(this).find('p').text('Hi 999')
    $(this).find('img').attr('src', '999.jpg')
}
});

DEMO

3 Comments

This won't change the img src
Ummm, still I feel it's inefficient :)
thanks dude, but it does not replace data-width value :(

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.