user3856818
user3856818

Reputation: 11

How to insert html element inside another element which already have some html?

I have an html structure like this.

<ul class="foo">
    <li class="bar">
        <a href="bar.html">Bar Html</a>
    </li>
</ul>

Now I want to rewrite the html using jquery as

<ul class="foo">
     <li class="bar">
          <span class="spanclass">
               <a href="bar.html">Bar Html</a>
          </span>
     </li>
</ul> 

So my question is how can I achieve this using jquery, I simply need to insert an html element inside an html element so that the content of the html still be there inside the newly inserted html.

If I Rephrase the code like this

<ul class="foo">
     <li class="bar">
        <a href="bar.html">Bar Html</a>
        <ul class="sub foo">
            <li class="sub bar">
                <a href="sub-bar.html">Sub Bar Html</a>
            </li>
         </ul>
    </li>
</ul>

And I want to get the result like my previous question, then how should I proceed. The Result should be as below.

<ul class="foo">
     <li class="bar">
        <div class="divclass">
            <a href="bar.html">Bar Html</a>
            <ul class="sub foo">
                <li class="sub bar">
                    <a href="sub-bar.html">Sub Bar Html</a>
                </li>
            </ul>
        </div>
    </li>
</ul>

Upvotes: 1

Views: 113

Answers (2)

user3856818
user3856818

Reputation: 11

WrapInner method is the answer for my question.

$('ul.foo li.bar').wrapInner('<div class="divclass">')

Will product the below code.

<ul class="foo">
 <li class="bar">
    <div class="divclass">
        <a href="bar.html">Bar Html</a>
        <ul class="sub foo">
            <li class="sub bar">
                <a href="sub-bar.html">Sub Bar Html</a>
            </li>
        </ul>
    </div>
</li>

Upvotes: 0

j08691
j08691

Reputation: 208032

$('ul.foo li.bar a').wrap('<span class="spanclass">')

Will produce:

<ul class="foo">
    <li class="bar">
        <span class="spanclass"><a href="bar.html">Bar Html</a></span>
    </li>
</ul>

jsFiddle example

See: .wrap()

Upvotes: 6

Related Questions