moses toh
moses toh

Reputation: 13162

How can I remove and append element li?

My html code like this :

<ul class="list">
    <li id="thumb-view-1">view 1</li>
    <li id="thumb-view-2">view 2</li>
    <li id="thumb-upload-3">upload 3</li>
    <li id="thumb-view-4">view 4</li>
    <li id="thumb-view-5">view 5</li>
</ul>
<button id="test">Test</button>

My javascript code like this :

<script type="text/javascript">
    $('#test').on("click", function(e){
        var a = 3;
        for(var i = 1; i <= 5; i++) {
            if(i == a) {
                $('#thumb-upload-'+i).remove();
                var res = '<li id="thumb-view-'+i+'">view '+i+'</li>';
                $('#thumb-view-'+(i-1)).after(res);
            }

        }
    });
</script>

Demo : https://jsfiddle.net/oscar11/eb114sak/

It works

But my case is dynamic. var a has value between 1 - 5. So var a can have value 1 or 2 or 3 or 4 or 5

While ul tag has 5 li tag. And 5 li tag can have different id type

So in addition to the tag li above, I give an example of another form

Like this :

<ul class="list">
    <li id="thumb-upload-1">upload 1</li>
    <li id="thumb-view-2">view 2</li>
    <li id="thumb-view-3">view 3</li>
    <li id="thumb-view-4">view 4</li>
    <li id="thumb-view-5">view 5</li>
</ul>

etc

If like that, the result still wrong

It seems it should call the li element based on a

So if a = 3 then the third li tag is deleted and append

But, I'm still confused

How can I do it?

Upvotes: 0

Views: 90

Answers (2)

Saksham
Saksham

Reputation: 9380

A simple solution could be to use replaceWith and index as

var index = $( "ul.list" ).index( $("li[id^='thumb-upload']") );

This will get the index of li whose class starts with thumb-upload within your unordered list

$("li[id^='thumb-upload']").replaceWith('<li id="thumb-view-'+index +'">view '+index +'</li>';)

And the above statement will replace that list item with your custom HTML

Another simple solution is to just change the ID as I don't see other changes as

$("li[id^='thumb-upload']").attr('id', $("li[id^='thumb-upload']").attr('id').replace('upload','view'));

Upvotes: 1

mjw
mjw

Reputation: 1206

Instead of remove / append, try replaceWith:

$('#test').on("click", function(e){
    var a = 3;
    for(var i = 1; i <= 5; i++) {
        if(i == a) {
            var res = '<li id="thumb-view-'+i+'">view '+i+'</li>';
            $('#thumb-upload-'+i).replaceWith(res);             
        }           
    }
});

This will only replace matching #thumb-upload- elements, so it will handle your dynamic cases.

Upvotes: 1

Related Questions