Reputation: 7791
If I use the following code:
var output = '<div class="info"><span class="bus-number">468 (58247)</span></div>';
var span = $(output).find('span.bus-number').text();
console.log(span);
I can see the value
468 (58247)
in the console, but if I try to use the wrap() method with the following code:
var output = '<div class="info"><span class="bus-number">468 (58247)</span></div>';
$(output).find('span.bus-number').wrap('<b></b>');
console.log(output);
I can't obtain this html code:
<div class="info"><b><span class="bus-number">468 (58247)</span></b></div>
How can I obtain the string with the wrapped element?
Upvotes: 1
Views: 2277
Reputation: 115232
You are not updating the string just updating the jQuery object so grab HTML content from jQuery object using html()
method.
var output = '<div class="info"><span class="bus-number">468 (58247)</span></div>';
// create a div element with html content
output = $('<div/>', {
html: output
// get span
}).find('span.bus-number')
// wrap the span
.wrap('<b></b>')
// back to previous selector
.end()
// get the html content
.html();
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or use outerHTML
property of dom element.
var output = '<div class="info"><span class="bus-number">468 (58247)</span></div>';
// create jQuery object
output = $(output)
// get span element
.find('span.bus-number')
// wrap span with b
.wrap('<b></b>')
// back to previous selector and get dom object
// using [0] after get html content from dom
.end()[0].outerHTML;
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 3
Reputation: 613
Because output
is just a string which is immutable.
For example you can do
var output = '<div class="info"><span class="bus-number">468 (58247)</span></div>';
$output = $(output);
$output.find('span.bus-number').wrap('<b></b>');
console.log($output.text());
Upvotes: 0
Reputation: 62596
You can use the html()
function.
Note that the html()
function returns the INNER html of the element, so you need to wrap it with another element to get the html:
var output = '<div class="info"><span class="bus-number">468 (58247)</span></div>';
var span = $(output).find('span.bus-number').text();
console.log(span);
var span = $(output).find('span.bus-number').wrap('<b></b>');
console.log(span.parent('b').html());
console.log(span.parents('div.info').html());
console.log($('<div>').append(span.parents('div.info')).html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1