Jquery ( Javascript ) id selector query

I saw an implementation of ID selector like this:

$("*[id*=foo]").val()

Why is this being used and is it similar to the id selector in jQuery? What is the main difference? Please explain

Upvotes: 0

Views: 63

Answers (1)

Takit Isy
Takit Isy

Reputation: 10091

Updated answer

$("*[id*=foo]").val() isn't similar to $("#foo").val():

  • $("#foo") selects an element which id is “foo”.

  • $("*[id*=foo]") selects any element which id attribute contains “foo”.

Check this example, where I used input id="fooAndSomeText":

console.log( $("*[id*=foo]").val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fooAndSomeText" value="bar" disabled />


⋅ ⋅ ⋅

Old answer
Before the question was formatted properly, changing its meaning!

$("[id=foo]").val() and $("#foo").val() would do the exact same thing.
# is the shorthand to target an id.

The first syntax is longer here, and there is no reason to use it.

But, this syntax is very useful when you want to target an element with a specific attribute value. Check this example with an input:

console.log( $("[name=foo]").val() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="foo" value="bar" disabled />

Hope it helps.

Upvotes: 3

Related Questions