wow
wow

Reputation: 8239

How do I use jQuery replaceWith correctly

here is my menu code :-

<div class="menu">
 <ul>
   <li><a href="http://domain.com/">Home</a></li>
 </ul>
</div>

I want replace it using .replaceWith to be :-

<div class="menu">
 <ul class="something">
   <li><a href="http://domain.com/">Home</a></li>
 </ul>
</div>

I tried something like this : -

$('<div class="menu"><ul>').replaceWith('<div class="menu"><ul class="something">' + $(this).text() + '</ul></div>');

But it's not working

What is the correct code for this replacement?

Upvotes: 1

Views: 908

Answers (3)

Joko Wandiro
Joko Wandiro

Reputation: 1987

You can use it:

    $("ul").replaceWith("<ul class='something'><li><a href='http://domain.com/'>Home</a></li></ul>");

it works correctly.. Maybe value of attribute have to separated with single quote and syntax start and end with double quote..

Upvotes: 1

Jacob Mattison
Jacob Mattison

Reputation: 51052

When you create a jquery object using straight html code, it doesn't find matches for that code on the page; instead it creates a new element based on that html and wraps it in a jquery object. Consequently you can replace it all you like and it won't affect your page.

You need to first find the element on the page using jquery selectors ($("div.menu ul")) and then do something to it:

$("div.menu ul").addClass("something");

Upvotes: 1

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

The difference I'm seeing is just the class of <ul class="something">.

Can't you just addClass() to it?

$('.menu ul').addClass('something');

Upvotes: 2

Related Questions