开发者

In jquery: Use attr(“class”) value as a selector? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

In jquery: Use attr(“class”) value as a selector?

I have fields with multiple classes. I want to use one of those classes as a selector, how do I do this?

generic example:

<input id="from"/><div class="error from">errormessage</div>
<input id="to"/>
<div><input id="when" /></div><div class="error when">errormessage</div>

Because ther is a div.error with the class from, I want to add a certain cl开发者_Go百科ass to input#from and the same goes for the input called when. Note that "when" is wrapped in a div. Several variations like this are necessary for the page. Therefore, tree-traversal is not a suitable solution.


$('.error.from')

or

$('.from.error')

Note the lack of white-space between the two class-names .error and .from, which selects only those elements with both of the given class-names.

If there had been a space ($('.error .from')) then this would select an element of class from that is a descendant of an element of class .error.

You could, if you wanted to (though I can't think why you would), use hasClass():

$('.error').hasClass('from');

Though I think this is rather less efficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜