fc123
fc123

Reputation: 918

jQuery selector not working as I expected

I have a simple html

<div id="dCA" style="width: 200px; margin-right: 20px; float: left;">
    <ul>
        <li><a href="#" id="AL" onclick="cs('1', this);">Alberta </a></li>
        <li><a href="#" id="BC" onclick="cs('2', this)">British Columbia</a> </li>
        <li><a href="#" id="M" onclick="cs('3', this)">Manitoba</a> </li>
        <li><a href="#" id="NB" onclick="cs('4', this)">New Brunswick</a> </li>
        <li><a href="#" id="NF" onclick="cs('5', this)">Newfoundland</a> </li>
        <li><a href="#" id="NS" onclick="cs('6', this)">Nova Scotia</a> </li>
        <li><a href="#" id="On" onclick="cs('7', this)">Ontario </a></li>
        <li><a href="#" id="PEI" onclick="cs('8', this)">Prince Edward Is </a></li>
        <li><a href="#" id="Q" onclick="cs('9', this)">Quebec </a></li>
        <li><a href="#" id="SK" onclick="cs('10', this)">Saskatchewan </a></li>
    </ul>
</div>

And I am trying to access the "a" but it's giving me undefined.

I have no idea what I am doing wrong, any help will be appreciated

I am trying to access like this,

alert($("#dCA").find("ul>li>a:contains('" + "Alberta"+ "')").attr("id"));

Upvotes: 2

Views: 67

Answers (2)

giannisf
giannisf

Reputation: 2599

Put your code in $(document).ready

$(document).ready(function() {
      alert($("#dCA").find("ul>li>a:contains('Alberta')").attr("id"));

})

or add the script after the html.

Upvotes: 0

Sid M
Sid M

Reputation: 4354

Your code works and gives "AL", however there is no need of " + "Alberta"+ ". This also works

alert($("#dCA").find("ul>li>a:contains('Alberta')").attr("id"));

Fiddle: Demo

Upvotes: 1

Related Questions