如果一个元素的第一个子元素没有被一个文本节点超前,如何匹配它? [英] How to match first child of an element only if it's not preceeded by a text node?
本文介绍了如果一个元素的第一个子元素没有被一个文本节点超前,如何匹配它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图匹配一个div(使用jQuery)的h4,以便我可以删除它的顶部margin。但是,我只想匹配h4,如果它的顶部没有文本。例如,匹配:
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>
但不是这样:
<div>
Blah blah blah.
<h4>Header</h4>
...
</div>
我可以在jQuery中找到的最好的代码是:
The best code I could come up with in jQuery is this:
$("div h4:first-child")
b $ b
但是,不幸的是,匹配上述两种情况。是否还要指定你希望它是绝对的第一个元素,前面没有文本节点?
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?
推荐答案
<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
}
});
这篇关于如果一个元素的第一个子元素没有被一个文本节点超前,如何匹配它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文