Home > Net >  IS it possible to to put jquery attribs before html ones?
IS it possible to to put jquery attribs before html ones?

Time:09-26

I am using $html attrib for inserting data attrib to my index.html file using jquery. I have also typed attribs manually.

Now is it possible if I press f12 to see the $html attribs first before the manual attribs?

E.g

html data-id="Code" lang="en-PH"

i set lang attrib manually and data id code via jquery.

If I press f12 lang comes first before data id. I want data id first before lang.

Is it possible?

CodePudding user response:

It's possible, by iterating over all attributes that exist on the element and deleting them, then adding your own new attribute, then re-adding the originals...

const div = $('div')[0];

// Cache and remove existing attributes
const attribs = [];
for (const attrib of div.attributes) {
  attribs.push([attrib.name, attrib.value]);
  div.removeAttribute(attrib.name);
}

// Add your own
$(div).attr('dynamicAttrib', 'dynamicVal');

// Re-add original attibutes
for (const [name, value] of attribs) {
  $(div).attr(name, value);
}
console.log(div.outerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div firstAttrib="firstValue"></div>

But whether a piece of code works or not should not depend on attribute order. It's somewhat convoluted and doesn't accomplish anything, and could even cause problems; I'd recommend not bothering.

  • Related