Reputation:
I want to check if following code is dynamically created or not :
<div id="js_contact_error_message" style="display: block;">
<div class="error_message"> <!-- For this div only I want to apply the above written inline css-->
Please enter full name
</div>
How should I check this in jQuery? If it's present execute the if condition.
Thanks.
The condition that <div class="error_message">...</div>
is present within <div id="js_contact_error_message" style="display: block;">...</div>
must get checked.
I tried below code but it didn't work for me:
if ($("#js_contact_error_message").find("div.error_message").length != 0) {
alert("Bestow");
}
Upvotes: 1
Views: 797
Reputation: 2553
Try,
For using if-else
condition.
if($("#js_contact_error_message").find(".error_message").length > 0)
{
alert("div present");
}
else
{
alert("div not present");
}
But as you stated in your question, you want to apply specific inline css. Make a class for the style what you have and you can use the ollowin code.
$("#js_contact_error_message").find(".error_message").addClass("your_style_class");
This code will apply your css class only for those div
s which match the condition.
EDIT:
If you want to add your style to the div
, you can try defining it in your page, which will apply as soon as the div is added dynamically.
<style>
#js_contact_error_message .error_message
{
/*your inline style*/
}
</style>
Upvotes: 1
Reputation: 31
make sure your html composition is correct , opening and closing. Then try this code.
if($("#js_contact_error_message").length > 0)
{
$("#js_contact_error_message").find(".error_message").addClass("style_class");
}
Upvotes: 0
Reputation: 74738
You can do this:
var hasDiv = $("#js_contact_error_message div").length > 0 ? true : false;
$("#js_contact_error_message").toggle(hasDiv);
You need to place this line of code where you have done your js validations.
or you may try with this:
$(document).on('DOMSubTreeModified propertychange',function(){
var hasDiv = $("#js_contact_error_message div").length > 0 ? true : false;
$("#js_contact_error_message").toggle(hasDiv);
});
Upvotes: 1
Reputation: 350
You can check it in many ways.. few of them are :
Use $("#js_contact_error_message").has('div')
function of jquery to get the specific element Has in JQuery
If the error message div is the only div to be inside the main div then you can check it as :
Check the element $("#js_contact_error_message").html()
is blank or use $("#js_contact_error_message").children()
(Children in JQuery) to check if it has any childrens.
Hope this helps :)
Upvotes: 0
Reputation: 18600
if($("#js_contact_error_message .error_message").length > 0)
{
alert("div is present");
}
else
{
alert("div is not present");
}
Upvotes: 0