admin管理员组文章数量:1315792
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 badges2 Answers
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:
- 'this' inside the filter function refers to node
- 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.
-
Node.TEXT_NODE
is not available in IE. Hence using the magic number 3.
版权声明:本文标题:javascript - How to match first child of an element only if it's not preceeded by a text node? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741980961a2408392.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论