I am playing around with the JQuery keyword this.
I have come across something I do not understand. Here is my code:
<body>
<a id="link_1">jQuery.com</a>
<!-- adding JQUERY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my JavaScript -->
<script>
$("a").attr("href", "target_1");
$("a").attr("new_attribute", "new_attribute_value");
$(function ($) {
$("a").mouseenter(function(){
alert(this.id);
alert(this.href);
alert(this.new_attribute);
});
});
</script>
</body>
I want JQuery to return the id, href and my new_attribute as an alert message.
I can call the id on the keyword 'this' (with this.id) and it works as expected. I can also call the href on the keyword this (with this.href) and it works as expected (even though I set the value of href with JQuery only (an not inline)).
However with the new attribute "new_attribute" this kind of set & get does not work as expected.
my question: What am I doing wrong? Is it only possible to call 'certain /limited' attributes on the keyword 'this'.
It's because new_attribute is not a valid attribute.
Some built in attributes are mapped to properties, and when you do
this.id
you're really getting the id property, not the attribute, as that would be
this.getAttribute('id')
you could do
this.getAttribute('new_attribute')
but you should really be using data-* attributes, and not make up your own, but jQuery's data() maps data internally and doesn't add attributes, but in your case that's probably what you want, just store arbitrary data on the element
$("a").attr("href", "target_1");
$("a").data("new_attribute", "new_attribute_value");
$(function ($) {
$("a").mouseenter(function(){
alert(this.id);
alert(this.href);
alert( $(this).data('new_attribute') );
});
});
In this context this points to HTMLAnchorElement object, and the problem here is the difference between HTMLElement attributes and their properties. Simply saying, attributes are rendered as a part of HTML, and used for additional object declarative configuration from the side of HTML markup.
On the other hand, there are properties of the object, which not always have corresponding attributes. Sometimes they do, but in most cases - they don't.
You can set any arbitrary attribute to HTMLElement like you did with new_attribute, but this custom attribute value will not become an object property. So reading such custom attribute as property will yield undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With