0

Hi can someone convert this jquery in to plain javascript?

$("body *").each(function () { 
    $(this).html($(this).html().replace(/\[br\]/\g,'<br/>')); 
});

What it does is, it finds all [br] and then replace it with <br/>

The code above works perfectly in chrome but not in mozilla and IE so i need to execute it in plain javascript. many thanks to all!

3
  • Why on earth would you want to do this in the first place? O_o Commented Sep 8, 2011 at 8:30
  • jQuery iexists to make cross-browser development easier. There is another problem somewhere. Commented Sep 8, 2011 at 8:31
  • 2
    jQuery exists to help newbies in making errors. Commented Sep 8, 2011 at 8:43

4 Answers 4

2

Try this:

window.onload=function(){
  document.body.innerHTML = document.body.innerHTML.replace( /\[br\]/g,'<br/>');
}

ps. In your code, there is a bug: instead of /\[br\]/\g should be /\[br\]/g

Sign up to request clarification or add additional context in comments.

Comments

0

The problem was that you had an illegal character in your regular expression.

This works: $(this).html($(this).html().replace(/\[br\]/g,'<br/>'));

Live example: http://jsfiddle.net/tqksm/

10 Comments

this is what i like about stackoverflow.. so many answers in less than 10 minutes.. you guys rock!!.. thanks
@frank that's nice to hear, but what is the point of what you're doing in the first place? From where I'm standing, this looks completely pointless. What's the idea behind it?
in my web application, if I see these characters { } ; \n. i replaced it with [br] when it is saved in the database, so that when I print it in my web site it is replaced by the break line tag in html. That's it. Thanks
@frank - why dont you just replace those characters with <br/> before saving the to database. Saves some pretty intensive client-side work when displaying the data.
Oh yeah I remember, the web container replaces this characters with the &lt; and &gt;
|
0

the problem is not jQuery. You have first to take a reference to the current html content, then apply the replace and finally inject the new html:

$("body *").each(function () { 
    var $this = $(this);
    var html = $this.html();
    $this.html(html.replace(/\[br\]/\g,'<br/>')); 
});

1 Comment

This is the same as the OP code. You've just split it out over more lines
0

I think your missing the point here...rewriting it in plain Javascript is likely to only make it worse for you. One of jQuery's purposes is to take away all the pain that comes while writing Javascript that must work on all browser. So...I think you'd be best off if you start looking for an alternative approach on your jQuery code instead of rewriting it to plain Javascript.

Comments

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.