Reputation: 29
How can we access a value which is defined inside the element? I tried this code, but it's not working.
$(document).ready(function() {
console.log($("div#named").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="named" Items='10'>Hello World!!</div>
Upvotes: 0
Views: 39
Reputation: 337560
Assuming by 'value' you mean the 'Items' attribute, then use attr()
:
jQuery($ => {
console.log($("div#named").attr('Items'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="named" Items="10">Hello World!!</div>
However you should note that Items
is not a standard HTML attribute and will cause your HTML to be invalid.
The correct way to add any metadata to an element is to use a data
attribute instead. You can then read this using jQuery's data()
method:
jQuery($ => {
console.log($("div#named").data('items'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="named" data-items="10">Hello World!!</div>
Upvotes: 2