Stormchao
Stormchao

Reputation: 260

jQuery selector with a wild card selection of a HTML5 custom data attribute

I'm trying to use a selector to grab an element, then look through the children elements for any that contain a value in a custom data attribute. Then I would perform an action on those children elements with the value, in this example it would turn their background-color to yellow.

For example take the following example of HTML and JS

<div id="RoleUserMaster">
  <div id="RoleUser1">
    <label for="Role1">Role:</label>
    <select name="Role1" class="RoleSelect">
        <option value="1">Role1</option>
        <option value="2">Role2</option>
        <option value="3">Role3</option>
    </select>
    <label for="User1">User:</label>
    <select name="User1" id="selectMe">
        <option value="11" data-roleids="1">Smith</option>
        <option value="12" data-roleids="2 4">John</option>
        <option value="13" data-roleids="1 3">Richard</option>
    </select>
  </div>    
</div>

$('#selectMe').children('[data-roleids=*"1"]').css('background-color','yellow');

I thought this jQuery will first select the element, then it would look at it's children, and try and find any children where custom attribute data-roleids contains a character of '1'. You can also take a look at http://jsfiddle.net/7NAhD/2/ to see it in action.

Upvotes: 0

Views: 941

Answers (1)

Cyril N.
Cyril N.

Reputation: 39909

It works with this :

$(function () {
    $('#selectMe').children('[data-roleids~="1"]').css('background-color','yellow');
});

See http://api.jquery.com/attribute-contains-word-selector/

Upvotes: 1

Related Questions