Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery data attr not setting

This appears very simple but I cannot see why it's not working. The selector is correct however the div .faqContent is simply not being updated with the data-height attribute.

$('.faqItem .faqContent').each(function(){     var h = $(this).height();     $(this).data('height',h); }); 

I have checked that var h is correct, it is in colsole.log as correctly holding the height.

EDIT It's absolutely not conflict, and console shows no errors.

like image 405
ggdx Avatar asked May 08 '14 09:05

ggdx


People also ask

How to get attr value using jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

What is data() in jQuery?

The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector). data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.

How to get attribute name in jQuery?

To get the name, you'd use $(selector). attr('name') which would return (in your example) 'xxxxx' .


2 Answers

You will not be able to see it in the element inspector but it is there as jquery set the data attribute internally.

try console.log($(this).data('height'));

like image 40
Mohammad Adil Avatar answered Sep 22 '22 12:09

Mohammad Adil


The data function confuses a lot of people, it's not just you. :-)

data manages jQuery's internal data object for the element, not data-* attributes. data only uses data-* attributes to set initial values. It never sets data-* attributes on elements.

If you want to actually set a data-* attribute, use attr:

$(this).attr("data-height", h); 

But if you just want this information for future use, data is fine, just don't expect to see it in the DOM inspector, because jQuery doesn't write this information to the DOM.

like image 172
T.J. Crowder Avatar answered Sep 24 '22 12:09

T.J. Crowder