beefchimi
beefchimi

Reputation: 1308

jQuery Prepend Open Tag Append Closing Tag

Firstly, I am familiar with .wrapAll() and that is not what I need. I have some markup that I am not able to change and I need to wrap everything in a <li>.

Here is what I am trying to do:

$('nav[role="breadcrumb"] ul a').wrap('<li></li>');

$('nav[role="breadcrumb"] ul li:last').after('<li>');

$('nav[role="breadcrumb"] ul').append('</li>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<nav role="breadcrumb">
  <ul class="clearfix">
    <a href="http://eggaday.armystage.com/">Home</a>
    <a href="http://eggaday.armystage.com/health-care-professionals/">Health Care Professionals</a> Healthy Choices Cholesterol Kits
  </ul>
</nav>

The problem is that jQuery closes each of these <li> tags. Here is the original markup:

<nav role="breadcrumb">
  <ul class="clearfix">
    <a href="http://eggaday.armystage.com/">Home</a>
    <a href="http://eggaday.armystage.com/health-care-professionals/">Health Care Professionals</a> Healthy Choices Cholesterol Kits
  </ul>
</nav>

As you can see, I have some loose text at the bottom of this <ul> and I am trying to get it wrapped in an <li>.

Upvotes: 0

Views: 826

Answers (3)

Kevin B
Kevin B

Reputation: 95022

jQuery only works with complete elements, you can't append just a closing or opening tag.

If the ul doesn't have any other list items, you could simply use wrapInner

$('nav[role="breadcrumb"] ul').wrapInner("<li />");

If it does contain LI's, the easiest way would be to detach them, wrap inner, then append them.

var $lis = $('nav[role="breadcrumb"] ul > li').detach();
$('nav[role="breadcrumb"] ul').wrapInner("<li />").prepend($lis);

Upvotes: 0

devnull69
devnull69

Reputation: 16544

.contents() will get all the children, including the text nodes

$('nav[role="breadcrumb"] ul').contents().filter(function() {
   return $.trim($(this).text())!=="";
}).wrap('<li/>');

EDIT: Added the filter method to get rid of the whitespace text nodes

Upvotes: 2

mawcsco
mawcsco

Reputation: 624

Try creating your <li> first and then append your selector to it:

var $li = $('<li>').append('nav[role="breadcrumb"] ul a');

Then use $li to replace or append anywhere you like.

Upvotes: 0

Related Questions