3

I want to cancel any links and add extra attributes to each one. Below is how I've achieved this.

function anularEnlaces(){
    $('nav a').each(function(){
        var href = $(this).attr('href');
        var id = $(this).attr('id');
        $(this).attr('href','javascript:void(0)');
        $(this).attr('hrefnot',href);
        $(this).attr('nivel','uno');
        $(this).attr('seccion','dos');
    });
}

My question is, is that a valid/recommended way to add custom atributes?

3 Answers 3

7

Not like that. If you are using the HTML5 doctype you can use the new data-* attributes, and then use the jQuery data method:

$(this).data("hrefnot", href);

And HTML:

<a href="somewhere.html" data-hrefnot="something">A link</a>

If you don't need to store data on your tags initially, then it doesn't matter whether you use the HTML5 doctype or not (jQuery's data method will still work).

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

2 Comments

but if i do this i can't see the current values in firebut. is that normal?
Yes, that's normal. jQuery stores data internally (so that you still have valid markup if you're not using an HTML5 doctype).
3

Valid if you are using HTML5, you can add your own custom data attributes data-:

HTML5 Custom Data Attributes (data-*)

and you can use jQuery's $.data to read and modify them.

Comments

2

No, you should use data() instead for custom element attributes, and attr() ( or better yet prop() ) for standard html attributes .


Example of data() usage :

<a hred="some/url" data-custom="value">test</a>

// getter
var customValue = $('a').data('custom');
var customUndefined = $('a').data('testing');

Now customValue contains "value" string, and customUndefined contains undefined

// setter
$('a').data('custom', 'test');
$('a').data('testing', true);

Comments

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.