3

I have an html div element, which contains lot of HTML-5 data- attributes to store extra

data with element. I know that we can use removeAttr of jquery to remove specific attribute,

but i want to know that is there any way to remove data- all atonce?

2 Answers 2

7

No, you have to loop through them and remove them individually. E.g.:

var $div = $("selector for the div"),
    attrs = $div[0].attributes,
    name,
    index;
for (index = attrs.length - 1; index >= 0; --index) {
    name = attrs[index].nodeName;
    if (name.substring(0, 5) === "data-") {
        $div.removeAttr(name);
    }
}

Live copy | source

...or something along those lines.

Sign up to request clarification or add additional context in comments.

Comments

6

Not aware of any wholesale way of doing this. You'd have to loop over the element's attributes with something like

var el = document.querySelector('p');
for (var i=0; i<el.attributes.length; i++)
    if (/^data-/i.test(el.attributes[i].name))
        el.removeAttribute(el.attributes[i].name);

2 Comments

Likewise you - not far away!
there's an error here, when you remove the attribute, the index changes, so you may skip two data attributes in a row. you have to { el.removeAttribute(el.attributes[i].name); i--; } or loop from the last to first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.