Reputation: 14119
I know how to accomplish this if I can identify this element using a selector
:
$("selector.class")
But what if my selector is the keyword this
? Obviously $(this".class")
isn't going to work, and I don't want to use $(this).children(".class")
because then I need to extract the HTML of the element using .html()
, and while I know that there will only be one element of this class in the selected element (I'm writing the HTML), JQuery doesn't, and it assumes that children()
returns several elements when used with a class (at lease I think that's what it does, because
$(this).children(".class").html()
returns undefined
).
Is there an other way I could do this?
Please feel free to ask for clarification, I understand this may not seem clear to some.
EDIT: some of you asked for clarification, so here it is. Let me rephrase the question: normally, when I ask JQuery to get me some elements, and give it a class as a selector it assumes I will get more than one element back and therefore $(".selector").html()
doesn't work, because you can't get the HTML of several elements (at least that's my theory). Instead, I want it to recognise that in this case I am only getting 1 element back, and treat is as such. My restriction is that part of my selector is this
. I hope that helped!
Upvotes: 1
Views: 224
Reputation: 6675
Really this
isn't a selector, but I think you can do:
$(".class", this)
This is an example of supplying the context
argument to the jQuery
($
) function
For example (jsfiddle here), HTML:
<div id="dis">hello
<div class="cls">
hi</div></div>
<div class="cls">
goodbye</div>
jQuery:
$(function () {
$('#dis').click(function () {
alert(
$('.cls', this).html());
});
});
will alert "hi" when the "dis" div is clicked.
Upvotes: 3
Reputation: 6741
Jquery is just a layer on top of JavaScript.
Just use raw javascript to get what you're looking for.
var childOfThis = this.querySelector('.myClass');
Upvotes: 1
Reputation: 707416
It isn't entirely clear to me what question you're asking so here are several different options:
To search for any subordinate tags (in the DOM tree with this
as its root) that match a desired selector:
$(this).find(".myClass");
Or, if you're just trying to see if the this
element has a particular class name, you can use:
if ($(this).hasClass("myClass")) {
// this element has the desired class
}
or, if the selector is more complicated than just a class, you can use .is()
like this:
if ($(this).is("selector")) {
// this element matches desired selector
}
Upvotes: 5