简体   繁体   中英

jQuery how to find class of an element which has a particular action

Hi I need to find the class of an element which matches a particular pattern. Basically what I am trying to do is add custom text to the end of form in a framework based product.

All instances of the product have the same

<form action="/cart" method="post" class="...">
</form>

I need to find the class of the form element in each such instance so that I can traverse to the last child and add my piece of text. Is it possible using jQuery alone? Thanks

Using jquery you can find any element by an attribute by wrapping it with []

$('[action="/cart"]')

This is where the attribute equals the value, but you can do contains by adding * before the = like so:

$('[action*=cart]')

Here's a list of attribute selectors:

https://api.jquery.com/category/selectors/attribute-selectors/

Then get the attribute for class:

$('[action="/cart"]').attr('class')

Quick sample here:

https://jsfiddle.net/op7bv8Lu/


If you want to get the last element you can add :last to the selector.

$('[action*=cart]:last').attr('class')

Again, sample here:

https://jsfiddle.net/xzpag6up/

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