JavaScript

How to Get the Index and Value (Text) of an li Tag Element Using jQuery this

In this article, we will introduce how to use jQuery this to get and display the index and value (text) of the clicked li tag element.

CSS to Get and Display the Index and Value of the Clicked li Tag Element

Adjust as necessary.

<style>
body{
	font-family:Verdana,"Hiragino Kaku Gothic Pro","ヒラギノ角ゴ Pro W6",Osaka,"MS Pゴシック",Arial,sans-serif;
	padding: 0;
	margin: 0;
}
h1{
	font-size:18px;
	line-height:1.6em;
	text-align:center;
	font-weight:normal;
	padding:10px 0;
}
.clWrap{
	width:700px;
	margin:0 auto;
	text-align:left;
}
#txtoutput{
	width:600px;
	margin:0 auto;
	color:#F00;
	text-align:center;
	font-size:20px;
}
li{
	padding:3px 0;
	cursor:pointer;
	font-size:20px;
}
li:hover{
	color:#999;
}
</style>

JavaScript to Get and Display the Index and Value of the Clicked li Tag Element Using jQuery this

Load the jquery.min.js (v1.7.1) file. When you click an li tag, it will get the index and value of the element and output the information to the tag with id=”txtoutput”.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
	$("li").click(function () {
		$("#txtoutput").text(($("li").index(this)+1)+" th li tag element 「"+$(this).text()+"」 .")
	});
});
</script>

HTML to Get and Display the Index and Value of the Clicked li Tag Element

Prepare li tags and click an li tag to get the index and value of the element and output the information to the tag with id=”txtoutput”. Adjust as necessary.

<div class="clWrap">
    <h1>Click an li tag to get and display the index and value.</h1>

	<div id="txtoutput">The clicked element will be displayed here.</div>

    <ul>
    <li>CSS</li>
    <li>Facebook</li>
    <li>HTML5</li>
    <li>JavaScript</li>
    <li>PHP</li>
    <li>SEO</li>
    <li>WordPress</li>
    <li>Others</li>
    <li>Smartphones</li>
    </ul>

</div><!--/clWrap-->

Demo Page to Get and Display the Index and Value of the Clicked li Tag Using jQuery this

Demo page to get and display the index and value of the clicked li tag using jQuery this

Although we usually think we know how to use this, I realized that I only had a vague memory of it when I actually tried to use it.

 
※ Please use this at your own risk. Do not reuse the Google Analytics tag within the demo page tags.