sergio sergio - 3 months ago 11
jQuery Question

How do I retrieve data stored with JS dot notation from jQuery?

I have a script that stores data in an LI element, with JS, with

testel = document.getElementById('#myLi');
testel.angle = 20;


How do I retrieve that value with JQ?
I tried creating a new reference to the element like
$('#testel').angle
or
$('#testel').data('angle')
but nothing works.

Where is that data stored? Is it even possible?

Answer Source

How do I retrieve that value with JQ?

Two ways:

  1. Get it from the raw DOM element:

    var a = $('#testel')[0].angle;
    //                  ^^^-------- Gets the raw DOM element from the jQuery object
    
    var a = $('#testel').get(0).angle;
    //                  ^^^^^^^-------- This does too
    
  2. Use prop:

    var a = $('#testel').prop('angle');
    

Where is that data stored?

That's called an "expando" property. It's stored on the raw DOM element. It's generally best to avoid using them when you can (to avoid conflicting with new standard properties that may be defined, to avoid conflicting with other scripts on the page). When you can't, it's best to use just one of them (usually referring to an object that you put other properties on if you need more information).

I tried creating a new reference to the element like $('#testel').angle or $('#testel').data('angle') but nothing works.

jQuery's data function stores information in a different area (to avoid expando issues). If you can, I'd suggest changing the code setting the value to set it via jQuery's data:

$('#testel').data('angle', 20);

...and then of course you can retrieve it the same way:

var a = $('#testel').data('angle');

As A. Wolff points out in a comment below, your code is a bit mismatched. You say you're doing this to set it:

testel = document.getElementById('#myLi');
testel.angle = 20;

...but then trying to use this to retrieve it:

$("#testel").angle // (and such)

Your getElementById code looks for an element with the ID #myLi (including the # at the beginning, as part of the id). While that's valid (you can do that in HTML; not in CSS), it's relaly unlikely you actually have:

<li id="#myLi">...</li>

in your document. You probably don't want the # in the getElementById call. (What you give getElementById is an ID string, not a CSS selector).

Regardless, you'll want the id you use when setting and when retrieving to match. So if it's myLi, use getElementById("myLi") and $("#myLi").