smith
smith

Reputation: 23

id contains specific string name in Jquery

I've a tmp variable. If a tag id contains tmp string want to addClass. How to do?

 $(document).ready(function () {
  var tmp = "#lnkPage" + id;

   $("#pageingdiv").children().each(function (n, i) {
        var id = this.id;
      //if (id.contains(tmp)) {
       // $(id).addClass('box');
        //}
    });
 });

 <div id="pageingDiv">
        <a id="CPH_Content_C002_lnkPage1" ></a>
        <a id="CPH_Content_C002_lnkPage2" ></a>
        <a id="CPH_Content_C002_lnkPage3" ></a>
        <a id="CPH_Content_C002_lnkPage4" ></a>       
    </div>
</div>

Upvotes: 1

Views: 19669

Answers (5)

Jai
Jai

Reputation: 74738

Try this:

 var tmp = "lnkPage" + id; // <-----remove the hash '#'

 $('[id$="'+tmp+'"]').addClass('box');

Upvotes: 0

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

You can use jQuery( "input[id*='value']" ) Selector to check if its contain specific string as ID.

Tested Code

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

    $(function()
    {
        $( "a[id*='lnkPage']" ).addClass('SampleClass');
    });

</script>


<div id="pageingDiv">
    <a id="CPH_Content_C002_lnkPage1" ></a>
    <a id="CPH_Content_C002_lnkPage1" ></a>
    <a id="CPH_Content_C002_lnkPage1" ></a>
    <a id="CPH_Content_C002_lnkPage1" ></a>
</div>

Upvotes: 1

Debasish Chowdhury
Debasish Chowdhury

Reputation: 188

Try this

var tmp = "lnkPage1";
$("a[id*='"+tmp+"']").addClass('box');

Upvotes: 0

Gung Foo
Gung Foo

Reputation: 13558

Look at the Attribute starts with, Attribute ends with and Attribute contains Selectors. They will help you select all the elements you want directly without the need to call any other functions than .addClass(). :)

Upvotes: 2

asifsid88
asifsid88

Reputation: 4701

use indexOf()

if(id.indexOf(tmp) !== -1)
{
    $(id).addClass('box');
}

Moreover you should not have elements with same ID, you should use class instead

Upvotes: 4

Related Questions