Sergei Mozhaisky
Sergei Mozhaisky

Reputation: 3

JQuery problem with html() handling in Opera

I have following JS code (stripped to minimal size where problem still exists)

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="debug">this is <em>test</em></div>
<script type="text/javascript">
    var string1 = $('#debug').html();
    var string2 = string1.replace(/<em>/g, '<strong>');
    string2 = string2.replace(/<\/em>/g, '</strong>');
    $('#debug').html( string2 );
</script>
</body>
</html>

In Firefox everything works and <em> tags are replaced with <strong>.

But in Opera <em>'s are stay in place. Furthermore, any other HTML tags are not captured by regexps at all.

Is there any way to fix this behaviour? I need not only to replace tags, but to parse their content too (href attributes for example).

Upvotes: 0

Views: 861

Answers (3)

Gumbo
Gumbo

Reputation: 655129

Don’t use string methods when you can use DOM methods:

$("#debug em").each(function() {
    var newElem = document.createElement("strong");
    for (int i=0; i<this.childNodes.length; ++i) {
        newElem.appendChild(this.childNodes[i]);
    }
    this.parentNode.replaceNode(newElem, this);
});

Upvotes: 1

Sharebear
Sharebear

Reputation: 395

Your regular expressions aren't matching in Opera as it has normalised all HTML tags to uppercase try with //gi

However if you are doing more changes ("parsing their content"), I really would recommend doing proper DOM manipulation and not using regular expressions.

Upvotes: 0

Phil Ross
Phil Ross

Reputation: 26090

Opera returns tags as uppercase, e.g. <EM>. You need to change your regular expressions to work case-insensitively:

var string2 = string1.replace(/<em>/gi, '<strong>');
string2 = string2.replace(/<\/em>/gi, '</strong>');

Upvotes: 3

Related Questions