user1231561
user1231561

Reputation: 3359

How to add class to <li> located within a .html() variable?

I have a variable from where I save the HTML of a certain div:

var menu = $(".menu").html();

The saved html() = var menu looks as followed:

<li>
    <a href="#">item 1</a>
</li>
<li>
    <a href="#">item 2</a>
</li>

The two <li>'s are then copied over to another div

otherDiv.append(menu);

The issue: I want to add a class to each of the <li>'s contained in the .html() before I append them to otherDiv. The original <li>'s can't be touched and needs to remain in original state.

Upvotes: 0

Views: 503

Answers (4)

guest271314
guest271314

Reputation: 1

Try utilizing .append( function ) , jQuery.parseHTML

var menu = $(".menu").html(), name = "other-menu";
$("#otherDiv").append(function() {
  return $.parseHTML(menu).map(function(html) {
    html.className = name;
    return html.outerHTML
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul class="menu">
<li>
    <a href="#">item 1</a>
</li>
<li>
    <a href="#">item 2</a>
</li>
</ul>
<ul id="otherDiv">
</ul>

Upvotes: 0

JFK
JFK

Reputation: 41143

Another approach without .clone() could be

var menu = $(".menu").html();
otherDiv.append(menu).find("li").addClass("test");

The original li elements remain untouched. I don't see the difference adding the class after the elements are appended though.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

One approach:

var menu = $('.menu')
    // cloning the found element(s), preserving event-handlers:
    .clone(true, true)
    // finding the descendant <li> elements:
    .find('li')
    // adding the 'newClass' class-name to those found <li> elements:
    .addClass('newClass')
    // returning to the original selection ('.menu'):
    .end()
    // retrieving the innerHTML:
    .html();

var menu = $('.menu').clone(true, true).find('li').addClass('newClass').end().html();

$('#otherElement').html(menu);
li a {
  color: #f00;
}
li.newClass a {
  color: #0f0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
  <li>
    <a href="#">item 1</a>
  </li>
  <li>
    <a href="#">item 2</a>
  </li>
</ul>

<ol id="otherElement"></ol>

References:

Upvotes: 1

Noah B
Noah B

Reputation: 331

Try jQuery's .clone():

var menu = $(".menu").clone().html();

It will create a deep copy, and then you can add the class to each of the contained <li>. That way you won't alter the original elements.

Upvotes: 0

Related Questions