Dharmesh
Dharmesh

Reputation: 973

Select td which contains a (Anchor) tag using jquery

I have an HTML code as given below. I want to select all td which contains a(anchor) as an immediate child (Here First TD tag) using jQuery.

<table>
  <tr>
    <td><a href="abc.aspx">ABC</a></td>
    <td>Second Level<span> >> </span>
        <div>
          <table>
             <tr>
               <td><a href="efg.aspx">EFG</a></td>
             </tr>
          </table>
        </div>
    </td>
 </tr>

Upvotes: 4

Views: 14019

Answers (7)

allen213
allen213

Reputation: 2277

Select the anchor using css child selector to check that the anchor is a child of a td then call parent

$('td > a').parent();

Upvotes: 2

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14737

Remember that jQuery has the :has() pseudo-selector.

$('td:has(> a)')

This will select all <td> elements with an immediate <a> child.

Upvotes: 3

dknaack
dknaack

Reputation: 60516

Description

Many ways to do this

You can use the parent css selector or jQuery's parent() function. Check out the sample and this jsFiddle Demonstration

Sample

  1. ​$("td > a").parent()
  2. $("td > a:parent")

More Information

Upvotes: 5

levi
levi

Reputation: 3521

var listOfTD = $("table td > a").parent();

This gives you all td having anchor as an immediate child, from the table. My advice is to give id to the table than you should write:

var listOfTD = $("#tableid td > a").parent();

Upvotes: 0

Daniele
Daniele

Reputation: 1081

If you give an #id to your table, you can do something like this:

$(function(){
    myTds = [];
    $('#mytable td>a').each(function(){
        myTds.push($(this).parent())
    })

//do stuff with your tds
});

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76890

something like

$('td').filter(function(){
    if($(this).children('a').length > 0){
        return this;
    });

Upvotes: 0

sp00m
sp00m

Reputation: 48837

This should do the trick:

$("td > a").parent();

Upvotes: 4

Related Questions