skip to Main Content

I am using jQuery replaceWith() method to replace some content from the html. Its working fine. But I want to change the data attribute value once replaceWith() has been done.

So basically I am getting this from my ajax response

UpdatedItem = '<li data-cart-key="XXX" data-item-name="Test" data-item-price="$111.00" data-item-key="XXX"><span class="cart-action-wrap"><a class="edit-cart-item" data-cart-item="XXX" data-cart-key="XXX" data-cart-action="edit">Edit</a><a class="remove-cart-item" data-cart-item="XXX" data-cart-key="XXX" data-cart-action="remove">Remove</a></span></li>';

Now I am using replaceWith() here like this

$( 'ul.custom-contents' ).find( 'li.updated' ).replaceWith( UpdatedItem );

Here I wanted to use methods like update data attribute value, remove class, add class after replaceWith() has been done.

So can someone tell me is there any way available to do this? Any help and suggestions would be really appreciable. Thanks

2

Answers


  1. You can create a jQuery object inside replaceWith, do the operations and return it. Use .find() for nested elements:

    $( 'ul.custom-contents' ).find( 'li.updated' ).replaceWith( fucntion(){
       let obj = $(UpdatedItem)   
       obj.addClass("..")
       obj.data("cart-key", "..")
       obj.data("item-name", "..")
       obj.removeClass("..")
    
       //Find <a> with class "edit-cart-item"
       obj.find("a.edit-cart-item").addClass(...)
       obj.find("a.edit-cart-item").data("item-name", "..")
       return obj;
    });
    
    Login or Signup to reply.
  2. you can solve like this.

    UpdatedItem =
      '<li data-cart-key="" data-item-name="Test" data-item-price="$111.00" data-item-key="XXX">updated</li>';
    divElement = document.createElement("div");
    divElement.innerHTML = UpdatedItem;
    element = divElement.firstElementChild;
    $("ul.custom-contents").find("li.updated").replaceWith(element);
    
    element.setAttribute("data-item-name", "myValue");
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    </head>
    
    <body>
    
    
      <ul class="custom-contents">
        <li class="updated">old</li>
        <li class="">old</li>
        <li class="">old</li>
      </ul>
    
    
      <script src="app.js"></script>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search