1

Possible Duplicate:
Remove elements with only a   space using jQuery

I have an automatically generated HTML feed that is filled with garbage... I am trying to clean it up a bit and would like to use jquery to strip out some of the bad code. So for example on an average page buried in the code there are close to 200x:

<div align="center"> </div>

If there was some sort of id or class element, these would be easy to get rid of. But I can't think of a way to find them without anything actually in them. Can I search by attribute? Or better yet is there a way to find by HTML code...

1
  • 3
    Are you intending to clean it up after it is downloaded to the browser using client-side scripting? Why bother? Commented Feb 2, 2013 at 20:45

2 Answers 2

1

If you are trying to simply remove all empty DIV elements, or DIV's with only a single space, then you could do this:

$('div').map(function() {

    if( $(this).html().length <= 0 || $(this).html() == " ")
    {
        return this;
    }

}).remove();

This iterates through all of the div's on your page and if they match a certain criteria (they are empty or only have a whitespace) then it removes them from the DOM.

This should give you a starting point. If you wanted to only check the DIV's with an align property of "center" then you would do this:

$('div:[align="center"]').map(function() {

    if( $(this).html().length <= 0 || $(this).html() == " ")
    {
        return this;
    }

}).remove();

jQuery's map() function can be great when a simple filter, or attribute comparison will not suffice.

You can read more about it here.... http://api.jquery.com/map/

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

Comments

0

There is a jQuery attribute selector

For your example:

jQuery( "div [align='center']" )

3 Comments

whitespace in CSS selectors is significant. Are you sure you want all [align=center] that are descendants of some div?
I am only answering the question "Can I search by attribute?" and showing how to do it with his single example. He hasn't said exactly what he wants to do. Maybe he will replace all of them with one <div />.
I need to do a lot of styling on it, and I would like to work with clean HTML. I probably don't need to strip garbage out, but for my own sake, I would like to.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.