扩展How to get a text before given element using jQuery? - 如何将此文本实际插入另一个段落?
http://jsfiddle.net/frank_o/fqwow5rr/
HTML:
<p>Text here <a href="#">URL</a></p>
<!-- Should be:
<p>Text here</p>
<p><a href="#">URL</a></p>
-->
JS:
var text = $('a').parent().html();
var regex = /(.*)<a/;
text = text.match(regex)[1];
console.log('Extracted text: ' + text);
# Uncaught TypeError: undefined is not a function
text.clone().append('<p></p>');
答案 0 :(得分:1)
使用字符串值覆盖text
变量。见固定示例:
var $text = $('a').parent();
var regex = /(.*)<a/;
var eText = $text.html().match(regex)[1];
console.log('Extracted text: ' + eText);
$text.after($('<p>', {
text: eText
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text here <a href="#">URL</a>
</p>
如果您只想移动链接元素(a
),只需将其插入新段落即可:
var $a = $('a');
var $text = $('a').parent();
$text.after($('<p>', {
html: $a[0].outerHTML
}));
$a.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text here <a href="#">URL</a>
</p>