1.追加
.insertBefore()在现有元素外部、之前添加内容; .prependTo()在现有元素内部、之前添加内容; .appendTo()在现有元素内部、之后添加内容; .insertAfter()在现有元素外部、之后添加内容。
$(document).ready(function() { $('back to top').insertAfter('div.chapter p'); $('').prependTo('body');});
2.包裹
.wrapAll()把所有脚注都包含;
.wrap()将每一个脚注分别包装。
$(document).ready(function() { $('span.footnote') .insertBefore('#footer') .wrapAll('');});') .wrap('
3.迭代
.each():这个方法接受一个回调函数,这个函数会针对匹配的元素集中的每个元素都调用一次 。
$(document).ready(function() { var $notes = $(''); });});').insertBefore('#footer'); $('span.footnote').each(function(index) { $('' + (index + 1) + '').insertBefore(this); $(this).appendTo($notes).wrap('
4.反向
.before和insertBefore;
.append和appendTo;
$('Hello
').appendTo('#container'); $('#container').append('Hello
');
5.串联
.join('')
$(document).ready(function () { var $notes = $(''); });});') .insertBefore('#footer'); $('span.footnote').each(function (index) { $(this) .before([ '', '', index + 1, '' ].join('')) .appendTo($notes) .append([ ' (context)' ].join('')) .wrap('
6.复制
.clone()
在默认情况下, .clone()方法不会复制匹配的元素或其后代元素中绑定的事件。不过,可以为这个方法传递一个布尔值参数,将这个参数设置为true,就可以连同事件一起复制,即.clone(true) 。
$('div.chapter p:eq(0)').clone().insertBefore('div.chapter');
7.setter 和 getter
.html()
.text()
$(document).ready(function () { $('span.pull-quote').each(function (index) { var $parentParagraph = $(this).parent('p'); $parentParagraph.css('position', 'relative'); var $clonedCopy = $(this).clone(); $clonedCopy .addClass('pulled') .find('span.drop').html('…').end()//drop类文本改为省略号... .text($clonedCopy.text())//获取纯文本,原文本的效果会移除,如加粗等 .prependTo($parentParagraph); });});
总结:
(1) 要在HTML中创建新元素,使用$()函数。(2) 要在每个匹配的元素中插入新元素,使用: .append() .appendTo() .prepend() .prependTo()(3) 要在每个匹配的元素相邻的位置上插入新元素,使用: .after() .insertAfter() .before() .insertBefore()(4) 要在每个匹配的元素外部插入新元素,使用: .wrap() .wrapAll() .wrapInner()(5) 要用新元素或文本替换每个匹配的元素,使用: .html() .text() .replaceAll() .replaceWith()(6) 要移除每个匹配的元素中的元素,使用: .empty()(7) 要从文档中移除每个匹配的元素及其后代元素,但不实际删除它们,使用: .remove() .detach()