如果元素的第一个子元素不在文本节点之前,它如何匹配?(How to match first child of an element only if it's not preceeded by

编程入门 行业动态 更新时间:2024-10-26 21:35:44
如果元素的第一个子元素不在文本节点之前,它如何匹配?(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 } });

更多推荐

本文发布于:2023-08-04 14:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   节点   个子   文本   match

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!