Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how can I find if an id has a specific string?

Tags:

jquery

I have a table and I want to know if its last td its id contains a certain string. For example, if my last td has id "1234abc", I want to know if this id contains "34a". And I need to do that in a 'if' statement.

if(myLastTdId Contains "blablabla"){ do something }

Thanks!!!

like image 437
André Miranda Avatar asked Mar 12 '09 23:03

André Miranda


People also ask

How do you select element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do you check if the ID exists in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

What is ID selector in Javascript?

The #id selector selects the element with the specific id. The id refers to the id attribute of an HTML element. Note: The id attribute must be unique within a document. Note: Do not start an id attribute with a number. It may cause problems in some browsers.


2 Answers

You could use the "attributeContains" selector:

if($("#yourTable td:last-child[id*='34a']").length > 0) { 
   //Exists, do something...
} 
like image 104
Christian C. Salvadó Avatar answered Sep 21 '22 18:09

Christian C. Salvadó


This is easily done with indexOf and last-child.

<table id='mytable'>
<tr>
  <td id='abc'></td>
  <td id='cde'></td>
</tr>
</table>

<script>
if($('#mytable td:last-child').attr('id').indexOf('d') != -1) {
   alert('found!');
}
</script>

Here it would alert 'found' because d appears in the string cde

like image 41
Paolo Bergantino Avatar answered Sep 18 '22 18:09

Paolo Bergantino