In this post we will see how to write selector string with multiple attribute values. For example, I have <ul>
element with a number of child <li>
elements,
have placed this <ul>
element inside <div>
with id='#divItems'
. An example layout may be like this:
<div id="divItems"> <ul> <li id="1" data-accountid="1" data-branch="1"<Item1>/li> <li id="2" data-accountid="1" data-branch="1"<Item1>/li> <li id="3" data-accountid="1" data-branch="3"<Item1>/li> <li id="4" data-accountid="2" data-branch="1"<Item1>/li> <li id="5" data-accountid="2" data-branch="2"<Item1>/li> <li id="6" data-accountid="3" data-branch="1"<Item1>/li> <li id="7" data-accountid="3" data-branch="2"<Item1>/li> <li id="8" data-accountid="3" data-branch="3"<Item1>/li> <li id="9" data-accountid="4" data-branch="1"<Item1>/li> <li id="10" data-accountid="4" data-branch="2"<Item1>/li> </ul> </div>
In jQuery you can select desired element for single attribute value (say id
), like this:
var liObject = $("#divItems ul li[id='2']);
You can also find by your own custom data attribute if it is being specified with the element, lets say each li
element has attribute data-accountid
. Syntax will be same.
var liObject = $("#divItems ul li[data-accountid='3']);
Take another step, you can specify multiple attributes in selector string. Lets say you can have multiple li
elements with data-accountid='3'
,
but you also want to narrow down your filter criteria by further looking for another attribute data-branchid
.
Here is how you can specify multiple attributes.
var liObject = $("#divItems ul li[data-accountid='3'][data-branchid='1']);
Similarly you can add any number of attribute filters in selector string.
I hope this helps some of you who get stuck with a similar problem.
No comments:
Post a Comment