How to match first child of an element only if it&

2019-05-09 02:49发布

问题:

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?

回答1:

<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
    }
});


回答2:

$("div h4")
    .filter(function() {
    var prev = this.previousSibling;
        return (!prev 
            || prev.nodeType !== 3
            || (prev.nodeType == 3 && prev.nodeValue.match(/^\s*$/)));
    })

Edit: Fixed it. Works in Firefox, IE8

Notes:

  1. 'this' inside the filter function refers to node
  2. both H4s have a text node before them. I think browsers insert text nodes everywhere they find whitespace and line break. In this case we select only the ones that are not whitespace-only.
  3. Node.TEXT_NODE is not available in IE. Hence using the magic number 3.