简体   繁体   中英

Add div element in ul list

I have some <li> elements, like this:

<ul class="some_class">
    <li></li>
    <li></li>
    ...
    <li></li>
</ul>

And in my css file I have:

.some_class > li

I want to change some of that li elements by jQuery. My idea is to have something like this:

<ul class="some_class">
    <div id="some_id">
        <li></li>
        <li></li>
    </div>
    ...
    <li></li>
</ul>

And change its by $("#some_id").html() . But its fails, because of css. I don't want to change css, cause its template css, and it's become very difficult to make changes in it.

Is there some other methods to perfom this?

Given the two pieces of source code you provided, your problem is not the CSS per say, but the way you changed the DOM, making the CSS invalid:

Solution 1:

Change:

.some_class > li

To:

.some_class li 

Because in your code manipulation your <li></li> are now direct descendants of some_class your CSS is broken. In CSS > means direct descendant.

Solution 2:

If you don't want to change the CSS just add a class to the <li> you want to change, but do not nest them inside another div.

Note: given the comments about invalid HTML: Solution 2 will not cause a problem with your HTML, and for solution one, replace DIV for another UL

There are lots of ways to target elements, and especially with jQuery this is a breeze.

Of course you can just add a class to each of the elements you want to target, but there are lots of ways to do it without changing your markup at all. For example, you can select using the actual index of the element within the parent using eq(); use pseudo classes like first-child, last-child; use jQuery extensions like :even or :odd; use nth-child to select repeatable patterns like every third element (nth-child:(3n+3))...

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