最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to match first child of an element only if it's not preceeded by a text node? - Stack Overflow

programmeradmin1浏览0评论

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 e 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?

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 e 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?

Share Improve this question edited Dec 14, 2011 at 15:29 Lightness Races in Orbit 385k77 gold badges666 silver badges1.1k bronze badges asked Feb 18, 2009 at 17:49 cdmckaycdmckay 32.3k25 gold badges86 silver badges114 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3
<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
    }
});
$("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.
发布评论

评论列表(0)

  1. 暂无评论