最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to remove all Attributes by attribute name starts with - Stack Overflow

matteradmin7PV0评论

I would like to remove all the attributes that attribute name starts with 'data-val' in the fields that has a class 'read-only-state'

 jQuery("[data-val^='tr']" )  

This will give attribute 'data-val' value that starts with 'tr'

But i need to remove all the attributes that starts with 'data-val' in the matched elements.

How can i do it?

I would like to remove all the attributes that attribute name starts with 'data-val' in the fields that has a class 'read-only-state'

 jQuery("[data-val^='tr']" )  

This will give attribute 'data-val' value that starts with 'tr'

But i need to remove all the attributes that starts with 'data-val' in the matched elements.

How can i do it?

Share Improve this question edited Feb 6, 2013 at 14:58 Murali Murugesan asked Feb 6, 2013 at 14:27 Murali MurugesanMurali Murugesan 22.6k18 gold badges75 silver badges122 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You can use vanilla javascript's attributes for this:

$('.read-only-state').each(function() {
   // get the native attributes object
   var attrs = this.attributes;
   var toRemove = [];
   // cache the jquery object containing the element for better performance
   var element = $(this);

   // iterate the attributes
   for (attr in attrs) {
     if (typeof attrs[attr] === 'object' && 
         typeof attrs[attr].name === 'string' && 
         (/^data-val/).test(attrs[attr].name)) {
       // Unfortunately, we can not call removeAttr directly in here, since it
       // hurts the iteration.
       toRemove.push(attrs[attr].name);
     }
   }

   for (var i = 0; i < toRemove.length; i++) {
     element.removeAttr(toRemove[i]);
   }
});
Post a comment

comment list (0)

  1. No comments so far