Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13998

Difference between div[id=testing] and div[id$=testing] in jquery

HTML

<div id="testing">MY TEDT</div>
<div id="testing1">MY TEDT Number 1</div>
<div id="testing2">MY TEDT Number 2</div>

JQUERY

$('div[id=testing1]').css("display", "none");

I have used the above jquery code for hiding the div with id testing. It is working fine. Look at the following code.

$('div[id$=testing1]').css("display", "none");

This code also doing the same. I just want to know what is the purpose of $ using here? Because without $ also it is working fine.

Fiddle DEMO

Upvotes: 1

Views: 2013

Answers (5)

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

The first one select the elements with id testing1. It will always select only one element. It will be better to use,$('#testing1').css("display", "none"); since the id is unique.

Second code will select the elements with id, ending with testing1. This may select multiple elements.

Example. Second code will selects an element with id testtesting1. Because it has testing1 in the end.

Upvotes: 2

Ashley Medway
Ashley Medway

Reputation: 7301

$ is an ends with selector.

So you are correct that it has no use in your example, but here:

$('div[id$=ting1]').css("display", "none");

The id="testing1" is still hidden.

If you want to select elements by ID you should use: $('#testing1') as this form of ID selector is much faster.

Documentation here.

Upvotes: 1

Ashish Mehta
Ashish Mehta

Reputation: 7426

$('div[id=testing1]').css("display", "none");

is Selects all elements whose id value is testing1

and

$('div[id$=testing1]').css("display", "none");

is matches every element whose id value ends with a testing1

Upvotes: 2

ssut
ssut

Reputation: 441

$ is ends with.

I recommend to use $('#testing1') instead of $('div[id=testing1]'). (first selector is much faster)

Upvotes: 1

Jai
Jai

Reputation: 74738

Here:

$('div[id$=testing1]').css("display", "none");

$ says the id which ends with testing1 apply the css to it with display:none;.

In the regular expression you often see these characters:

^ : starts with
$ : ends with

so if you have an element with id some thing like this:

<div id="div-box">New Division</div>

these three are similar:

$('#div-box')
$('[id^="div"]')
$('[id$="box"]')

Upvotes: 2

Related Questions