Jimenemex Jimenemex - 1 year ago 52
HTML Question

How to get attribute value from HTML tags

I'm trying to get the value from the HTML tag. Not the text itself, but the attribute value. What am I doing wrong?



$('label').click(function() {
$('p').text(($(this).val()));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label value="hello">click</label>
<p></p>




Answer Source

Use data-* it allows you to use any arbitrary string. ex. data-value="hello". This is valid and universal on on any element AFAIK. The jQuery method to use is .data()

$('label').click(function() {
    $('p').text($(this).data('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label data-value="hello">click</label>
<p></p>