Select tr of a table with javaScript if it has a text

4

I am trying to change the style of an entire specific row if, within that row, an element contains a plain text that I receive through a parameter in the url.

With this code I extract the variable hidden in the url.

var query = window.location.search.substring(1);
var idDeny = query.split("=");
var psf=idDeny.pop();

Now I want to look for that variable within the rows of my table and when I find it: that I modify its style by shading it a little to indicate to the user where that element is.

I was trying something like this:

$("#tSearch tr").find(psf) {
    $(this).css('background-color','#000');
});
    
asked by Yami 16.08.2016 в 00:43
source

2 answers

2

To find text within an element in row

You can use the selector :contains() . So:

$("#tSearch").find('tr:contains("' + psf + '")')

We select the table with id tSearch and then select the rows that contain the text assigned to psf .

Code

// A modo de ejemplo, buscamos la fila que tiene el texto "B1"
var psf = 'B1';

// Cambiar el fondo
$("#tSearch").find('tr:contains("' + psf + '")')
             .css('background-color','#ff0');
  
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="tSearch">
  <tr id="titulo">
    <th>A</th>
    <th>B</th>
  </tr>
  <tr id="fila1">
    <td>A1</td>
    <td>B1</td>
  </tr>
  <tr id="fila2">
    <td>A2</td>
    <td>B3</td>
  </tr>
</table>
    
answered by 16.08.2016 / 01:15
source
2

Optimizing the code a bit, and taking into account that you are working with the attribute id , you can use the selector directly (you should have only one element with said id in your document):

Solution with jQuery

var query = window.location.search.substring(1);
var idDeny = query.split("=");
var psf = idDeny.pop();

$('#' + pst).css('background-color','#000');

Solution with pure javaScript

var query = window.location.search.substring(1);
var idDeny = query.split("=");
var psf = idDeny.pop();

document.getElementById(psf).style.backgroundColor = "#000";
    
answered by 16.08.2016 в 02:36