Posted on: 21.08.2020 Posted by: Alex D Comments: 0

$(this) works correctly with find(), $(this,’tag’) and children().

The this operator is very convenient to use. But it may not work correctly in some cases.

If your tag contains a tag and you refer to the parent tag by class, then there may be an error.

Perhaps the page has another tag with the same class.

<DIV class="level">
	<P>111</P>
</DIV>
<DIV class="level">
	<P>222</P>
</DIV>
<DIV class="level">
	<P>333</P><P>444</P>
</DIV>
<DIV class="level">
	<P>555</P><P>666</P><P>777</P>
</DIV>

There are 4 div and all have a level class.

//this is not the correct code.
var tx = $(this).text();
//this is the correct code.
var tx = $(this).find("p").text();
var tx = $(this).children("p").text();
var tx = $(this,"p").text();

You must use operators .find(“tag”), .children(“tag”) or .$(this,”tag”) with $(this).

Sample code.

<DIV class="level">
	<P>111</P>
</DIV>
<DIV class="level">
	<P>222</P>
</DIV>
<DIV class="level">
	<P>333</P><P>444</P>
</DIV>
<DIV class="level">
	<P>555</P><P>666</P><P>777</P>
</DIV>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<SCRIPT>
$(".level").on("click", function() {
	var tx = $(this).find("p").text();
	alert(tx);
});
</SCRIPT>

DEMO

Categories:

Leave a Comment