如果元素的第一个子元素不在文本节点之前,它如何匹配?(How to match first child of an element only if it's not preceeded by a text node?)
我正在尝试匹配div的h4(使用jQuery),以便我可以删除它的上边距。 但是,我只想匹配h4,如果它上面没有文字。 例如,匹配这个:
<div> <h4>Header</h4> ... </div>但不是这个:
<div> Blah blah blah. <h4>Header</h4> ... </div>我在jQuery中提出的最佳代码是:
$("div h4:first-child")但不幸的是,这与上述情况相符。 反正有没有指定你希望它是绝对的第一个元素,之前没有文本节点?
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?
最满意答案
<div> <h4>Header</h4> ... </div> <div> Blah blah blah. <h4>Header</h4> ... </div>然后你可以使用以下。
$('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>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 } });更多推荐
发布评论