1

How can I get value of data-dial-code using jQuery?

<ul class="country-list>
    <li class="country preferred active" data-dial-code="1" data-country-code="us">...</li>
</ul>

<ul class="country-list>
    <li class="country preferred active" data-dial-code="48" data-country-code="pl">...</li>
</ul>

I can get this element like this bacause I have to list with the same class but I need the second one:

$('.country-list .active')[1]

1
  • Here is an introduction attr(). Commented Nov 13, 2019 at 8:44

4 Answers 4

2

You can follow below two ways to read data attribute value of second li only

BTW: you have missed closing double quote for class of ul -- <ul class="country-list">, so correct it in your source code

$(function(){
   console.log('Data with "data" ' + $('ul.country-list li.country:eq(1)').data('dial-code'));
   //OR
   console.log('Data with "attr" ' + $('ul.country-list li.country:eq(1)').attr('data-dial-code'));
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
    <ul class="country-list">
        <li class="country preferred active" data-dial-code="1" data-country-code="us">
        </li>
    </ul>

    <ul class="country-list">
        <li class="country preferred active" data-dial-code="48" data-country-code="pl">
        </li>
    </ul>

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

Comments

1

You should use the .attr() function as described in jQuery docs:

https://api.jquery.com/attr/

Comments

1

Just like this.Since you only need which is active li right?

var ddcode=$('.country-list .active').attr('data-dial-code');

Comments

1

if you need the second one with the class active

var value = $('ul.country-list li.active:eq(1)').data('dial-code');

Comments

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.