May 5, 2012

Jquery contains selector, regex

Question by Jernej Pangeršič

This is my code:
Let’s say that name is set to john

$("#first_table").append($('#second_table').find("tr:contains(" + name + ")"));

Basically I have 2 tables on my website. I would like to move elements from first to second, but only if they match completely. How can i do that?

Now if I have (for example) john john #1, john #2 in my table, they would all be moved. I would only like to move john and leave john #1 and john #2
I would like the code to work to match the variable name EXACTLY.
So if name is JOHN it must only get JOHN. If it’s JOHN #1, it must only get JOHN #1 and so on. Is this possible?

Answer by Starx

Since every name case is valid to :contains(" + name +") statement, it matches all of them.

Try this, with a :not to omit the one with “#”

$("#first_table").append($('#second_table').find("tr:contains(" + name + "):not(:contains('#'))"));


If you want to be precise about the values inside. Then use something like this

$("#second_table tr td").each(function() {
   if($(this).text() == 'John') { 
     $(this).closest("tr").appendto($("#first_table")); //find the cotaining tr and append to another table

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!