views:

5198

answers:

2

I'm trying to match the h4 of a div (using jQuery) so that I can remove it's top margin. However, I only want to match the h4 if it has no text on top of it. For example, match this:

<div>
  <h4>Header</h4>
  ...
</div>

but not this:

<div>
  Blah blah blah.
  <h4>Header</h4>
  ...
</div>

The best code I could come up with in jQuery is this:

$("div h4:first-child")

But that, unfortunately, matches both the above cases. Is there anyway to specify that you want it to be the absolute first element, with no text nodes before it?

+3  A: 
<div>
    <h4>Header</h4>
    ...
</div>

<div>
    Blah blah blah.
    <h4>Header</h4>
    ...
</div>

then you could use the following.

$('div').each(function() {
    var me = this;
    if ($(me).html().toUpperCase().indexOf("<H4>") == 0){ //check to see if the inner html starts with an h4 tag
        $(me).children('h4')... //do what you need to do to the header
    }
});
Jon Erickson
Looks really similar!
RSolberg
Unfortunately, there's no guarantee that the text above the h4 will be a `<span>`. It might just be a naked text node.
cdmckay
Cameron - what is stopping you from putting the text in a span or a div or a p?
RSolberg
maybe you could use the .html() value to check the contents of the html. if the .html() value starts with '<h4>' then you will know that you have a match
Jon Erickson
Russell - I'm not in complete control of the HTML. Users can modify it through a web form.
cdmckay
I have changed my if statement above to check to see if the inner html starts with an <h4> tag or not. maybe that will work for you?
Jon Erickson
i just tested in IE7 and it works. you may want to do a trim on the inner html returned by .html() to make sure there is no whitespace.
Jon Erickson
That should probably work too... except I'm thinking you'd probably want `$(me).children('h4:first-child')` or else you might get extra h4 elements (if there was more than one in that div).
cdmckay
I think it might be more efficient to maybe match all the divs with h4:first-child, then do the same thing you did except using `.parent().html()...`.
cdmckay
I'm voting down for answer theft :)
RSolberg
definitely have a bunch of options to play around with. I'm glad it has helped you out though. good luck!
Jon Erickson
fyi, there is a $.trim() jQuery utility function that could be handy to trim that string.
Jon Erickson
+2  A: 
Chetan Sastry
I just tested it... no dice. It still matches both cases (in Firefox at least).
cdmckay
Botched up the filter function. I'm fixing it.
Chetan Sastry