I am still learning JS and HTML, and I want to know if I can use attributes that don't exist by default, can I add new one from html? can I add new one from JS?
Asked
Active
Viewed 7,330 times
1
-
2Yes. Just use HTML5 `data-` attributes. http://html5doctor.com/html5-custom-data-attributes/ – Terry Dec 16 '14 at 23:19
-
Thanks Terry, but how can I get an element after that where these attributes = something, for example: $("span[data-attribute='my value']") .. I have tried this but it's not working knowing my input has the following: – SharePoint Freak Dec 16 '14 at 23:23
-
1That is because you are selecting a `` element with the attribute of `data-attribute` whose value is `my value`. If you want to match the input, use `$("input[data-attribute='my value']")`. If you want to match the span element after that, use the general or immediate sibling selector: `$("input[data-attribute='my value'] ~ span")` or `$("input[data-attribute='my value'] + span")`. – Terry Dec 16 '14 at 23:30
-
oh sorry, they are both input, sorry, the code is like this $("input[data-attribute='my value']") – SharePoint Freak Dec 16 '14 at 23:31
2 Answers
3
Something like this should work:
var x = document.getElementById('yourid');
x.setAttribute("TestAttribute", "TestValue");

alec
- 396
- 1
- 6
-
-
1I would defer to the jQuery api: http://api.jquery.com/attribute-equals-selector/ The link above has a decent example. Searching "jQuery get element by attribute" will get you plenty of examples. – alec Dec 16 '14 at 23:28
-
2
You can set any attributes you want to your html elements.
If you use jQuery see: http://api.jquery.com/attr/#attr2
$( "#elementID" ).attr( "customAttr", "Anything you want" );
Without jQuery
var myElement = document.getElementById('elementID');
myElement.setAttribute("customAttr", "Anything you want");

rousseauo
- 720
- 7
- 22
-
How can I get the element that's using the custom attribute? $("span[data-attribute='my value']"); doesn't work – SharePoint Freak Dec 16 '14 at 23:34
-
Take a look at the [jQuery documentation](http://api.jquery.com/category/selectors/attribute-selectors/) to select with the attribute. Or you could add an ID to your element and select it by id. If it doesnt work, I recommend you recreate the problem on [jsFiddle](http://jsfiddle.net/). – rousseauo Dec 17 '14 at 13:30