0

I have a bug in my code and i try to remove it using jquery.

Some code:

<div id="content">
s
<div class="breadcrumb">
<h1>Test and etc</h1> etc etc....

I want to use jquery to remove the s (if exist...in some cases not)

I've tried

var cont = $('#content').html();

$('#content').html(cont.replace('/s\s(.*)/','$1'));

Seams that the code above is not working...some sugestions ?

2
  • 2
    Why can you not remove it from the HTML source directly? Commented Jan 9, 2015 at 9:26
  • You don't need the outer apostrophes when you use regex. cont.replace(/s\s(.*)/,'$1'). I'm not sure how well the regex itself works though Commented Jan 9, 2015 at 9:27

3 Answers 3

1

Don't use a regex to remove a textnode by running a replace on the HTML, target the textnode directly

var content = document.getElementById('content'),
    child   = content.firstChild;

if (child.nodeType === 3) { // if textNode
    content.removeChild(child);
}

FIDDLE

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

Comments

0

You do need to call the code when the DOM is ready. And remove the quotes.

$(document).ready(function(){
  var cont = $('#content').html();
  $('#content').html(cont.replace(/s\s(.*)/,'$1'));
});

Fiddle : http://jsfiddle.net/anj1x7xe/

Comments

-1

I don't understand, why won't you remove it directly from the HTML source?

Is the code automatically generated (aka you didn't manually write that 's' there)? Because if it is, I strongly suggest you correct the bug itself. What you're trying to do is covering up a bug, not fixing it. It's good practice to get to the source of a bug and fix it.

Alas, if you really want to do this: You need to specify when your script is called. Most likely, you want it put into the $(document).ready() event.

$(document).ready(function(){
  var cont = $('#content').html();

  $('#content').html(cont.replace('/s\s(.*)/','$1'));
});

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.