Jquery insertAfter()选择器的正确语法

时间:2011-11-27 21:18:22

标签: jquery html jquery-selectors

我有div

<div id="imgDIV"><h4>My Debug DIV</h4></div>

我希望在div的顶部插入调试消息,但在第一个h4之后,这样我就可以在顶部收到最新的消息。

$('My Debug Messages').insertAfter(the first `h4` of the DIV);

但无法正确使用语法来引用h4

我已经为h4提供了有效的ID,但想知道在h4中指定第一个div的正确语法。

2 个答案:

答案 0 :(得分:4)

要使用的选择器是:

.insertAfter('#imgDIV h4:first-child')

如果要插入纯文本字符串,则不能单独$()该文本,因为jQuery会将其视为选择器;你需要将文本包装在HTML元素中,然后附加它。例如,p

$('<p>My Debug Messages</p>').insertAfter('#imgDIV h4:first-child')

结果是:

<div id="imgDIV"><h4>My Debug DIV</h4><p>My Debug Messages</p></div>

答案 1 :(得分:2)

$( '#imgDIV' ).children( 'h4:first' ).after( 'Your message' );