2

I need to remove a period inside of a div that only has a class attribute (no id -- system generated page).

<div class="myClass">
Some text . 
</div>

I need to remove the period. How can this be accomplished using JavaScript?

0

2 Answers 2

4

Without jQuery, here is the old-school option:

var divs = document.getElementsByTagName('div');
for (var i=0,len=divs.length;i<len;++i){
  if (/(?:^|\s)myClass(?:\s|$)/.test(divs[i].className)){
    // Removes every period
    divs[i].innerHTML = divs[i].innerHTML.replace( /\./g, '' );
  }
}

With jQuery:

$('div.myClass').html(function(i,oldHTML){
  return oldHTML.replace( /\./g, '' );
});
Sign up to request clarification or add additional context in comments.

5 Comments

What about document.getElementsByClassName('myClass')?
@Rocket Or document.querySelectorAll(); both of these are not 'old-school', having been implemented only in newer browsers.
All good until you do a string replace on innerHTML, which has all kinds of potential problems if the <div> contains other elements.
@TimDown I agree in principle, but not with "all kinds of potential problems". a) The OP's example is pretty simple and clear; b) the only problems I can think of are 1. removing and re-adding elements will remove procedurally-bound event handlers, or 2. pulling out periods inside of attributes (changing names or classes). That's exceptionally unlikely to be a problem for this user, or most anyone who would need this odd JS-only hack.
Those were the two I had in mind also, so maybe I overstated it slightly. I think you're right that it's likely to be safe for this particular case, but I think doing string manipulation on innerHTML is generally dangerous, is used blindly by many developers and I'd prefer to see warnings when it's being encouraged.
1

If you're using jQuery, you can do this:

$(".myClass").html(function(i, html) { return html.replace(/\.$/, ""); });

2 Comments

It's not efficient to perform the query twice. You should either use the function form of html() (as in my answer) or var a = $('...'); a.html(a.html().replace(...));
Ah, I had no idea it had a function form! The more you know, thanks :)

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.