Home > Back-end >  What's the difference between 'form#myForm' and '#myForm' in Jquery?
What's the difference between 'form#myForm' and '#myForm' in Jquery?

Time:02-23

What's the difference between:

$("form#myForm")

and

$("#myForm")

when it comes to referencing and/or submitting a form in Jquery? I've seen it done both ways. Is there an important difference?

CodePudding user response:

Assuming it's a form, if there a difference?

Yes, there's a slight difference, but only on a page that is incorrectly using duplicate id values. form#myForm will only match an element of type form, even if there's another element with id="myForm" earlier in the document. #myForm (with jQuery) will match just the first one (although that behavior is not documented and shouldn't be relied upon, it's a by-product of a jQuery optimization; don't use duplicate id values at all).

Example:

console.log("#myForm matched: "   $("#myForm")[0].tagName);
console.log("form#myForm matched: "   $("form#myForm")[0].tagName);
<!-- DON'T DO THIS, `id` VALUES MUST BE UNIQUE IN THE DOCUMENT -->
<div id="myForm"></div>
<form id="myForm"></form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

But again: Don't do that.

The form#myForm selector is also more specific than the #myForm selector, but again, it shouldn't matter, because there should only be one matching element.

  • Related