0

I've got a div that will swap the position of the class name depending on where it is on the page. I'm trying to strip the header-section- text and header-type text so I just have payment or resource. But depending on where the class is I will sometimes get a space before or after the header-type class. In order to do this I'm calling .replace() 3 times there has to be a better more concise way of doing this instead of having three .replace methods. Any ideas?

 <div class="header-section-payment header-type"></div>
 <div class="header-type header-section-resource"></div>

JQUERY

   var headerCategory = $(this).closest('div[class*="header-section-"]')
   .attr('class')
   .replace('header-section-', '')
   .replace(' header-type', '')
   .replace('header-type ', '');

I learn best by code samples so please include where applicable. Thanks!

2
  • check out trim function, docs here. Commented Oct 26, 2013 at 20:35
  • Not sure if this is the end result you want but make sure you know about removeClass existence. Commented Oct 26, 2013 at 20:35

1 Answer 1

1

First off an extra space in the class name does absolutely no harm. Maybe if you were doing the same operation thousands of times you might worry about an accumulation of extra spaces, but it doesn't really cause a problem in any way.

For your particular situation, you can use jQuery's .removeClass("header-type") for that class name and then you won't have extra blanks to worry about when you just remove "header-section". That could work like this:

var headerCategory = $(this).closest('div[class*="header-section-"]')
   .removeClass("header-type")
   .each(function() {
        this.className = this.className.replace('header-section-', '');
    }); 

Please note that in your existing code, you are calling .replace(), but not assigning the result to anything and your code would not work if headerCategory had more than one DOM object in it either which is why I use .each() here.

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

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.