jQuery( '[attribute~=”value”]' )

jQuery API の jQuery( '[attribute~="value"]' ) は、attribute に指定した属性の値に、value に指定した値が含まれている、すべての要素を選択する。attribute に指定した属性が、スペースで区切られた複数の値を持っていても、 value に指定した値が存在すれば、選択する。

記述方法

jQuery( 'セレクター[属性~=値]' )

セレクターに一致した要素のうち、「属性」に指定した属性の値に、「値」に指定した値が含まれている、すべての要素を選択。

実装例(サンプル)

セル セル セル
セル セル セル
セル セル セル

実装例(サンプル)の動作について

「toggle」ボタンをクリックすると、class属性の値に「jquery-api-attribute-class」を含むセルの背景色が、ピンク色に変わる。

「toggle」ボタンを再度クリックすると、class属性の値に「jquery-api-attribute-class」を含むセルの背景色が、黄色に戻る。

実装例(サンプル)のソースコード

JavaScript

<script type="text/javascript">
<!--
jQuery( function() {
    jQuery( '#jquery-api-toggle' ) . toggle(
        function () {
            jQuery( '#jquery-api-attribute td[class~=jquery-api-attribute-class]' ) . css( {
                backgroundColor: 'pink',
            } );
        },
        function () {
            jQuery( '#jquery-api-attribute td[class~=jquery-api-attribute-class]' ) . css( {
                backgroundColor: 'yellow',
            } );
        }
    );
} );
// -->
</script>

CSS

<style>
<!--
.jquery-api-smaple-td {
    background-color: yellow;
}
-->
</style>

HTML

<button id="jquery-api-toggle">toggle</button>
<table id="jquery-api-attribute">
    <tr>
        <td class="jquery-api-smaple-td jquery-api-attribute-class">セル</td>
        <td class="jquery-api-smaple-td">セル</td>
        <td class="jquery-api-smaple-td jquery-api-attribute-class">セル</td>
    </tr>
    <tr>
        <td class="jquery-api-smaple-td">セル</td>
        <td class="jquery-api-smaple-td jquery-api-attribute-class">セル</td>
        <td class="jquery-api-smaple-td">セル</td>
    </tr>
    <tr>
        <td class="jquery-api-smaple-td jquery-api-attribute-class">セル</td>
        <td class="jquery-api-smaple-td">セル</td>
        <td class="jquery-api-smaple-td jquery-api-attribute-class">セル</td>
    </tr>
</table>

スポンサード リンク

カテゴリー: API, JavaScript, jQuery, セレクター, 属性 タグ: パーマリンク