简体   繁体   中英

check auto generated span class tag with Jquery

i am trying to check an auto generated span class="" content , which i will use it as a condition to determine whether i will show a message to the user or not

here is the span

<span id="sprytextfield1" class="textfieldInvalidFormatState">

what i tried here is to put a Div called email with an id so i can use the following

if ($('email').html('<span id="sprytextfield1" class="textfieldInvalidFormatState">'))
{

alert ("error");
}

but this did not work because if put the span inside my div email this will stop the JavaScript and result in error, because for some data condition i can not close the div at the end of the span.

is there any way to get the span class without putting all the span inside a div ?

Check: http://jsfiddle.net/pratik136/YY5RR/

This will let you get the class of all spans.

If you want to append a span to your div and still get a reference to it (so you can modify it further), I'd suggest doing like this:

$("#email").html(""); // optional: clear email
var mySpan = $('<span id="sprytextfield1" class="textfieldInvalidFormatState"/>').appendTo($('#email'));

Then you can add more things to the span, like text or other elements:

mySpan.text("some text");
mySpan.append('<a>some link</a>');

You mentioned you can't close the div after the span, I understood that you want to add more elements to it, is that correct? Just append (or prepend) them, after creating the span:

$("#email").append(someElement); // Will appear in the end, after the span
$("#email").prepend(someElement); // Will appear in the beginning, before the span

Update: re-reading your question, it's not clear to me what you're trying to check. Will the span be already in your document, and you just want to see whether or not it has a specific class (that you already know)? If that's the case, get the element (you have its id) and use hasClass on it:

if ( $("#sprytextfield1").hasClass("textfieldInvalidFormatState") ) {
    alert("error");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM