skzi
skzi

Reputation: 373

Data attribute value from first div using jQuery

This should be easy but I am stuck! I need to get a data attribute from the first div in html chunk obtained using ajax. The div can have other elements or text but it will always be the first item in the html chunk. The html will not contain head, body or other start elements.

Html looks like below.

<div data-code="US"><span style="background-color:red">test</span><br /></div>

The jQuery script looks like below.

function LoadCode(url) {
            $.get(url, function (data1) {
                var code = "";
                //code = $(data1 + ":first").data("code"); // did not work
                //code = $(data1).data("code"); // did not work
                alert(code);
            });
        }

Upvotes: 0

Views: 168

Answers (2)

Bruno Calza
Bruno Calza

Reputation: 2780

This should work

$(data1).data('code');

Upvotes: 1

Yehia Elhawary
Yehia Elhawary

Reputation: 598

You must get attribute from div like:

code = $(data1).attr("data-code");

Upvotes: 0

Related Questions