Adrian Cid Almaguer Adrian Cid Almaguer - 3 months ago 13
HTML Question

How to wrap an element in a html string var?

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?

Answer

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>