0

I am running an ajax call that returns some HTML as a string. For the purpose of this question I will call this <div class='abc'>ABC123</div> when I get this back I want to check and see if the class "abc" has a value and what that value is. However when I run a .find() I cannot find the class, I can find the div, but not the specific class. Just using the div is not adequate because in the real live code the HTML is very complex and has many divs and classes. Below is some JS that illustrates my point.

var x = "<div class='abc'></div>"; 
$(x).hasClass("abc"); // returns true
$(x).find(".abc"); // Returns empty array

Why is it that the first line returns true, but the selector cannot find the element?

Thanks!

0

2 Answers 2

3

Because $x is the div with class abc.

jquery .find() tries to find any children within the div.abc with class abc which it won't find.

This is more like it.

var x = "<div class='abc'><div class='def'></div></div>"; 
$(x).hasClass("abc"); // returns true
$(x).find(".def"); // returns $('div.def')
Sign up to request clarification or add additional context in comments.

1 Comment

That seems to be the issue. Thanks!
0

When we append html element to the page, sometimes JQuery can't find this element due to parent and child relationship.

For example: a button having class submit inside a div having id append_area and we want to run a function on click on this button. Then we can use the below code.

HTML Code:

<div id="append_area">
</div>

Jquery Code:

$("#results").delegate('.submit', 'click', function(){ });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.