Getting attribute set by a function jQuery - javascript

I have a function attached to the div #Browse's click event that toggles a variable isOpen to true or false. Another click event has the following statements
alert($("#Browse").attr('isOpen'));
alert(document.getElementById('Browse').isOpen);
The first one yields "undefined" while the second one says true or false and is correct. How can I get the value of isOpen using jQuery?

Use data attributes to both set and get the data:
// to set
$("#Browse").data('isOpen', true)
// to get
$("#Browse").data('isOpen')
Documentation
jQuery data method - http://api.jquery.com/data/

There is no "jQuery way" to do this, because isOpen is an ad-hoc property. If you are able to change how the property is set, follow the recommendations in Chris' answer.
Otherwise, the closest you can get is to use jQuery to get the DOM element, and then unwrap it:
alert($("#Browse")[0].isOpen);

With new versions of jQuery, you need to use .prop to get this.
alert($("#Browse").prop('isOpen'));

To get access to the dom element in jQuery, you have to get the element by its index in the jQuery collection: With an id, there's hopefully only one element in your collection, so you can use get(0)
$('#Browse').get(0).isOpen;
For more convinient setting of attributes on jQuery elements, just use the data method

Related

Jquery clone() doesn't clone new value set wit data()

Using jquery data() to set data attribute of an element, like so:
HTML:
<div id="some-el" data-number="0"></div>
JQ:
$("#some-el").data("number",1);
As we know, data changes variable internally. So inside inspector you cannot actually see that new value is 1. But this aside, if I do clone on the element with new data value, jquery clones original dom element without current data value!!!
$("#some-el").clone();
Results in <div id="some-el" data-number="0"></div> both internally and visibly!
I was thinking I could avoid this problem by simply using attr("data-number",1);
Anyways, I wanted to ask you if this is correct behaviour of dat()? Is what I'm seeing expected? and WHY?
I think clone can accept a boolean to indicate a Clone with data and events, so Clone(true) should work: http://api.jquery.com/clone/
Here's a fiddle that works: http://jsfiddle.net/2pdNL/
.data() is not setting the value in DOM.
The data- attributes are pulled in the first time the data property is
accessed and then are no longer accessed or mutated (all data values
are then stored internally in jQuery)
But here is a workaround, instead of using
$("#some-el").data("number",1);
Interact directly to DOM like
$("#some-el").attr("data-number",1);
JSFiddle
Also check this answer

jquery data do not match dom attribute

I have an weird issue with jquery data function. Here is the fiddle
As you can see I update the active data but I cannot see the dom data-active attribute value change, although I re-query the active data, It writes the changed value.
$.data() do not update the attribute on the dom when I inspect it.
jQuery data api does not depends on the element attribute although it uses data-<key> to fetch the initial value if it is available.
jQuery uses an internal javascript object to maintain the data value of objects
If you want to update the attribute then you will have to use .attr('data-<key>', '<value>')
You will need to use attr as .data will not update the actual DOM node attribute -
$($('li')[1]).attr('data-active', true);
http://api.jquery.com/data/

Why won't this function give me the name of the element it's bound to?

I have an some html elements defined with class="tab".
And in my jquery file, I have defined the following function:
$('.tab').mouseleave( function() {
alert($(this).name);
});
When I trigger the mouseleave, for the element of class "tab", with the name "Contact", I do get the alert - but it says "undefined". I was expecting to see "Contact".
What does $(this) give me - does it actually give me the DOM element?
NB. Ultimately, I want to be able to work out on what side ( north, south, east or west ) the mouse left the element. So I'm doing this alert thing to ensure that I actually have access to the width and height of that element. So far, I don't seem to have access to that info.
name is a native javascript method, you are working with $(this), which is a jQuery object, and not the native DOM element, that would be just this :
$('.tab').mouseleave( function() {
alert(this.name);
});​
FIDDLE
$(this) gives you a jQuery object that wraps the native DOM element.
this is the DOM element you seek.
this is where you may find a more comprehensive description.
The name is an attribute, right?
So check $(this).attr('name')
You are working with jQuery object, use attr or prop function to get attribute value:
$('.tab').mouseleave( function() {
// either should work
alert($(this).attr('name'));
alert($(this).prop('name'));
});
$('.tab').mouseleave( function() {
alert($(this).attr('name'));
});
jQuery allows you to get the width and the height like this:
$(this).height(); //is the computed height eg. 200 without the dimension
For your specific code example, try $(this).prop('name'); or $(this).attr('name'); //now deprecated
this will pick up foo from <input name="foo" />
You could also try this.name if your element has a name attribute, which should only be applied to input elements. However it may return undefined and throw an error if you don't have the attribute.
$(this) is a jQuery object with the DOM element inside it. this is the DOM element direct.
$(this) will give you the JQuery object.
this gives you the DOM element.
You can get the name by calling $(this).prop('name') if the "name" attribute is supported by that HTML element.
The "name" attribute is currently only supported by form elements (input, select, textarea, form); the "name" part of the name-value pairs that are sent to the server when a POST verb is sent to the server (i.e. you post a form with the "POST" method).
Further reading:
http://forum.jquery.com/topic/please-explain-attr-vs-prop-change-in-1-6
.prop() vs .attr()
http://timmywillison.com/2011/When-to-use-.attr()-and-.prop().html
It is because $ gives an array of wrapped elements. Thus $(this) will be an array with one element. $(this).attr("name") will give you the name since attr knows it is an array. If you want you can use $(this)[0].name or simply this.name

Add some properties to a <div> element

I want to add some properties to a <div> element. All of the below works except for the .data(). I cannot see it appear in Firefox/Firebug.
$('#menu-container')
.css('background-image','url("'+big_image+'")')
.addClass('click_2')
.data("new_link", "new_link.html")
.css('z-index',"99");
Am I doing it wrong?
data is not just any ordinary attribute you can add, it is a way to attach objects and data to DOM elements. You can't see it in the HTML source or in Firebug, but you can query it using .data()
The data itself is not stored on the element. It's actually stored in $.cache
.data() is working but it won't show up as an element's attribute.
If you wanted to see it working you can try console.log($('#menu-container').data('new-link'));
If attributes are what you want then you can do .attr('new-link','new-link.html')
Use
$('#menu-container').attr('data-new_link','new_link.html');
it will appear in firebug, and you can also use the expected jQuery behavior
$('#menu-container').data('new_link');
to retrieve the value stored..
But there is really no need to do it this way. It gets stored at the .data() collection, regardless of being added as an attribute to the DOM element..

jQuery label 'for' attribute selector

I am using Remy Sharp's labelover plugin for jQuery and I would like to exclude a label with the attribute for and value nature.
Here's an example of the code working:
$(document).ready(function() {
$('form.default label').labelOver('over');
});
and what I'm trying to do:
$(document).ready(function() {
$('form.default label').not($('label').attr('for','nature')).labelOver('over');
});
Can anyone see where I'm going wrong? Feels like I'm pretty close to what I need to do.
attr is not a selector, it's a function that gets the attribute value with attribute name as the 1st argument, or sets it with a new value if one is passed as a 2ng argument.
Also, you excluded labels after selecting them with your not call, because the selector label matched all labels, and attr as I said did not filter that.
To select based on attribute, use this:
$(document).ready(function() {
$("form.default label[for!='nature']").labelOver('over');
});
As you may have guessed, the [attribute='value'] is the selector for an attribute "equal" to some value, and [attribute!='value'] is the "not equal" version of it.
For reference see:
http://api.jquery.com/attribute-not-equal-selector/
For reference on all selectors:
http://api.jquery.com/category/selectors/
This is also referenced at my JavaScript & Web Dev Newsletter site.
.attr('for', 'nature') is setting the value for the for attribute to nature
To filter by attributes, use [attribute="value"]:
$('form.default label').not('[for="nature"]').labelOver('over')
working code: http://jsfiddle.net/3nQbr/1/
$('label').not('[for="nature"]').labelOver('over');

Categories