简体   繁体   中英

Manipulating first child inside DIV as an UL element in jQuery

Currently I have the below HTML elements.

<div class="ow_box_empty ow_stdmargin clearfix">
    <div id="avatar-console" class="ow_avatar_console ow_center">
        <div style="height: 190px; background: url(7.jpg) no-repeat;>
            <div style="display: none;" id="avatar-change">
                <a href="http://avatar">Change Avatar</a>
            </div>
        </div>
        <div class="user_online_wrap">
            <div class="ow_miniic_live"><span class="ow_live_on"></span></div>
        </div>
    </div>
</div>

I want to wrap the first DIV(inside DIV with id "avatar-console") with an LI tag and insert new LI tag at the end as shown below.

Below is the required ouput.

<div class="ow_box_empty ow_stdmargin clearfix">
    <div id="avatar-console" class="ow_avatar_console ow_center">
        <ul>
            <li>
                <div style="height: 190px; background: url(7.jpg) no-repeat">
                    <div style="display: none;" id="avatar-change">
                        <a href="http://avatar">Change Avatar</a>
                    </div>
                </div>
            </li>
            <li class="star">★</li>
        </ul>
        <div class="user_online_wrap">
            <div class="ow_miniic_live"><span class="ow_live_on"></span></div>
        </div>
    </div>
</div>

I tried the below code to start with but it gives unwanted results. I am not sure where and how to start on this.

$("#avatar-console div:first-child").append('<li class="star">★</li>') 

Fiddle Link: http://jsfiddle.net/Purus/U3KC8/

This should work:

http://jsfiddle.net/da4dz/

$("#avatar-console > div:first")
    .wrap('<ul><li></li></ul>')
    .closest('ul').append('<li class="star">star</li>');

您可以使用jQuery wrap()方法:

$("div:first-child", "#avatar-console").wrap("<ul><li></li></ul>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM