Check content of father's previous sibling [jQuery]

This is the table’s HTML code:


<table>
    <thead>
        <tr>
            <th><a href="">Column 1</a></th>
            <th><a href="">Column 2</a></th>
            .
            .
            .
        </tr>
    </thead>
</table>

Let’s say that, when I click on the link “Column 2”, I want to check if the previous column head contains the text “Column 1”. Why is this selector not working?


$(function() {
	$('th a').click(function() {
		 if ($(this).html() === 'Column 2' && $(this).parent().prev().children().html() === 'Column 1') {
			do something
		}
        })
})

If I understood it correctly, I have to find the link’s father element (parent()), then find the previous sibling (prev()), find its child (the other link) and finally check its text. However, this is not working…

It works for me, but if it doesn’t work for you it’s probably because of the .children(). That returns a collection of nodes, and not just one node. So you might want to add .eq(0) after .children() to just get the first one


$(function() {
	$('th a').click(function() {
		 if ($(this).html() === 'Column 2' && $(this).parent().prev().children().eq(0).html() === 'Column 1') {
			console.log('Ya!');
		}
	})
});

Even better would be to delegate it from the table (provided you’re on jQuery 1.4.2 +)

$(function() {

	$('table').delegate('th a', 'click', function() {
		 if ($(this).html() === 'Column 2' && $(this).parent().prev().children().eq(0).html() === 'Column 1') {
			console.log('Ya!');
		}
	});

});

Here’s a nice video on .delegate() (and the differences between .live() and .delegate(), might you be interested: YouTube - The Difference Between jQuery's Live() and Delegate() Methods

According to $(this).parent().prev().children().html()
you’re getting the html of all of the children, which is: “<a href=”“>Column 1</a>”

What about if you select the anchor from the context of that previous element, using:
$(‘a’, $(this).parent().prev()).html()

I’ve just realized that the code that I posted works for me too. The problem is that I had a conflicting statement in an else if branch :smiley:

I didn’t know that you could do such thing :open_mouth: