thetipsyhacker
thetipsyhacker

Reputation: 1422

jQuery data() and attr() methods, and JavaScript dataset property return undefined

I have this HTML:

<span class="price" itemprop="price" content="66.00">66.00</span>

I am trying to get the value of the content data attribute in the span, but I keep getting undefined instead of the price value.

I've tried using $(".price").data("content"), $(".price").attr("content"), $(".price").prop("content"), and pure JavaScript document.querySelector('.price').dataset.content; however all of these return undefined.

The only way I get an actual value is when there is only one product on the page, I add an Id to the span and use document.getElementById('price').getAttribute("content").

I created a JSFiddle: https://jsfiddle.net/01kqoje7/9/. Within this fiddle, the attrPrice variable is the only variable that gives a value, but in my code, even jQuery's attr() gives me undefined.

Why am I getting undefined when I'm trying to access the data attribute of my class?

P.S. I don't have any control over the naming convention of the data attributes.

Upvotes: 2

Views: 166

Answers (2)

random_user_name
random_user_name

Reputation: 26160

If you know that the attribute you are looking for is content, it is possible to use a jQuery has attribute selector:

For example:

// will select ALL items with content attribute:  
$('[content]').attr('content');

If you know you want ONLY items with a certain class on it, you can combine the class and attribute selectors like so:

// will select items with content attribute that have the price class:
$('.price[content]').attr('content');

As others have mentioned, using $('.price').data('content') requires that the attribute is prefixed with data- (such as data-content="66.00"), and can't be used in this situation.

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

It should be data-content instead :

<span class="price" itemprop="price" data-content="66.00">66.00</span>

NOTE : $(".price2").attr("content") should work if the element is loaded to the DOM so try to make usre that you're executing your code inside the ready function like :

$(function() {
     //Your logic here
});

$(function() {
  console.log( $(".price").data("content") );
  console.log( $(".price2").attr("content") );
  console.log( document.querySelector('.price').dataset.content );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="price" itemprop="price" data-content="66.00">66.00</span>
<span class="price2" itemprop="price" content="22.00">22.00</span>

Upvotes: 0

Related Questions