Martin AJ
Martin AJ

Reputation: 6697

How can I select the first specific inner element?

Here is my HTML?

<ul>
    <li>
        <a href="./link1">
            <div>something</div>
            <span><a href="./link2">link</a></span>
        </a>
    </li>
</ul>

And this is my jQuery code:

$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})

As you see, there is two <a> tags. And .find() refersh to both of them. While I just want to select the <a> which is right inside (one level) in the <li> tag. So expected result is ./link.

What alternative should I use instead of .find() ?

Upvotes: 0

Views: 61

Answers (5)

mahyard
mahyard

Reputation: 1238

Don't do so. How is the browser meant to know which link to follow? It'd be invalid HTML

I suggest you using this instead:

<a href="page1">start</a><a href="page2">middle</a><a href="page1">end</a>

As you can see start and end are linked to page1 but the middle points to page2.

Upvotes: 0

Parag Jadhav
Parag Jadhav

Reputation: 1899

Method 1: Using Jquery's children and first

$('#myList').on('click', function() {
  var link = $('#myList').children('a').first();
  console.log(link.attr('href'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
  <li id="myList">
    <a href="./link1">
      <div>something</div>
      <span><a href="./link2">link</a></span>
    </a>
  </li>
</ul>

Method 2: Using the immediate children selector >

$('#myList').on('click', function() {
  var link = $('li > a:first');
  console.log(link.attr("href"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
  <li id="myList">
    <a href="./link1">
      <div>something</div>
      <span><a href="./link2">link</a></span>
    </a>
  </li>
</ul>

Upvotes: 1

Peter
Peter

Reputation: 16923

the first specific element

What alternative should I use instead of .find() ?

$(this).find('a:first')

seems like only logical solution and easy to read by developer

Upvotes: 0

prasanth
prasanth

Reputation: 22500

Try with eq(0) .It will get the first a tag

Or

Do with first('a')

$(this).children().first('a').attr('href')

$('li').click(function(){
console.log($(this).children('a').eq(0).attr('href'))

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>click
        <a href="./link1">
            <div>something</div>
            <span><a href="./link2">link</a></span>
        </a>
    </li>
</ul>

Upvotes: 2

31piy
31piy

Reputation: 23859

You can use the direct descendant selector.

$('li').on('click', function(){ var link = $(this).find('> a').attr('href'); })

Upvotes: 2

Related Questions