1

I currently have an li like so:

<li value="100" data-cost="137.00"><span>100</span></li>

I am trying to access the data attribute cost value.
In this example I would like to get a return of 137.00

I am doing a console log of this since I thought this would work:

console.log($(this).closest("[data-cost]"));

My return shows the entire object and I can see the dataset there: enter image description here

The reason I'm using closest is because I currently need to select this li when it's clicked so I'm using span to select it.

This is the entire code block to select an element.

  $(function(){
    jQuery(".po-list li span").on("click", function(){
      var span = $(this).clone();
      var options_col = $(this).closest('.options-col');
      console.log($(this).closest("[data-cost]"));
      span.attr('class','cur-option-val');
      options_col.find('.cur-option-w .cur-option-val').replaceWith(span);
    });
  });

As I said above I was expecting this: console.log($(this).closest("[data-cost]")); to return just the value. I tried this:

console.log($(this).closest("[data-cost]").val());
console.log($(this).closest("[data-cost]").text());

Both of those returned the value of the span not of the data-cost

1 Answer 1

2

$(this).closest("[data-cost]") will just return the element with the attribute of data-cost - which you can see. Use the .data() method to extract the value:

$(this).closest("[data-cost]").data("cost");

This will return a string representation of what's in the attribute. If you need it as a number - cast it:

//Ignore this, casting wasn't needed as pointed out in comments
//let dataCost = +$(this).closest("[data-cost]").data("cost"); //the "+" will cast the string to a number

Edit: As Barmar pointed out, .data() will already do the parsing.

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need to cast it. .data() will try to parse it as JSON, and if it's valid it will return the parsed value.
@Barmar - Edited the post, didn't know that, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.