ARi
ARi

Reputation: 78

find elements having custom attribute with some specific value and replace it

I want to find all element which has attribute data-socketid with value abc and replace the value with xyz. How to do this.

please note that abc and xyz both are dynamically created when page refreshed

This is what I have done so far. But its not working.

HTML

<div id="chat-win" data-socketid="abc">
   <div class="close-conversation-box">                   
      <div class="text-right">                     
        <a id="end-chat" data-socketid="abc" >End Chat</a>
        <a id="stop_bot"  data-socketid="abc" >Stop Bot</a>
      </div>
   </div>
</div>

Script

var matchDataSocketId = $("[data-socketid$=abc]");
var len = Object.keys(matchDataSocketId).length;

for(var i = 0; i < len; i++) {
   $(matchDataSocketId[i]).attr('data-socketid', $(matchDataSocketId[i]).attr('data-socketid').replace(abc, xyz));
}

Any help, suggestion will be highly appreciated. Thanks in advance.

Upvotes: 1

Views: 350

Answers (2)

31piy
31piy

Reputation: 23859

Try this:

$("[data-socketid=abc]").attr("data-socketid", "xyz");

It simply iterates through matching elements, and changes the value of data-socketid attribute to xyz.

Please note that I've removed $ before = in your selector since you've mentioned that the matching elements should have abc as the value of their data-socketid attribute.

Upvotes: 1

Satpal
Satpal

Reputation: 133403

As per the code sampleimplies that it's a partial match/replacement, You can use .attr(fn) to update the attribute value

$("[data-socketid=$abc]").attr(function(_, value) {
   return value.replace('abc', 'xyz');
});

Upvotes: 2

Related Questions