Find and get the value of an element by its data attribute value using jQuery code

By | July 10, 2021

HTML5 data attributes has given us the capability add extra to an elements by using ‘data-‘ keyword as a prefix , which can be accessible from JavaScript/jQuery code. Now the question is, how can I get the value of an element by its data attribute values? answer is below.

For example, you have created a list of programming languages and you want to get the specific language name by data-id attribute.

<ul id="myMenu">
		<li data-id="1">JavaScript</li>
		<li data-id="2">jQuery</li>
		<li data-id="3">NodeJs</li>
		<li data-id="4">ReactJs</li>
	</ul>

The code to get the value of item from above list. You have to write your jQuery code as following:

<script type="text/javascript">
	$(function() {
	   var data_id = 2; // I want to get the second item
	   var data_value = $('[data-id="'+data_id+'"]').text();
	   alert(data_value); // it will output: jQuery
	});
  </script>

Here is the complete code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Find and get the value of an element by its data attribute value using jQuery code</title>
  <style>
	#myDiv{width: 300px;border: 15px solid green;padding: 50px;margin: 20px;}
  </style>
</head>
<body>
	<div id="myDiv" class="abc container inner_div">
	<h4>Welcome to Lipku Tutorials</h4>
	<ul id="myMenu">
		<li data-id="1">JavaScript</li>
		<li data-id="2">jQuery</li>
		<li data-id="3">NodeJs</li>
		<li data-id="4">ReactJs</li>
	</ul>
	</div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
	$(function() {
	   var data_id = 2;
	   var data_value = $('[data-id="'+data_id+'"]').text();
	   alert(data_value);
	});
	
  </script>
</body>
</html>

Hope, it will help you. 🙂