Mark Boulder
Mark Boulder

Reputation: 14297

Extract text from one paragraph and insert into another

Expanding on How to get a text before given element using jQuery? - how does one actually insert this text into another paragraph?

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>');

Upvotes: 1

Views: 68

Answers (1)

Ionică Bizău
Ionică Bizău

Reputation: 113425

You override text variable with a string value. See fixed example:

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>

If you only want to move the link element (a), just take it and insert it into the new paragraph:

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>

Upvotes: 1

Related Questions