简体   繁体   中英

Why Jquery $(#); doesn't work but Javascript document.getElementById works fine?

I have a set of fully functioning codes in Javascript with "document.getElementById". But when I change it to Jquery, it doesn't work (and there are no errors).

<!DOCTYPE html>
<html>
<head>
<style></style>
<script src="jquery-3.3.1.min.js"></script>
<script language="javascript">
    function formChk(){
    var success=true;
    var types = ["Western","Chinese","Local","Beverage"];
    var nameTxtBox=$("#name"); <!--This doesn't work-->
    var picturesTxtBox=document.getElementById("pictures"); <!--This works fine-->

The corresponding id="name" and id="pictures" are in the codes below:

<p><input type="text" id="name" name="name"></p>
<p><input type="text" id="pictures" name="pictures"></p>

There are no error messages in the console. However, the code doesn't run as per it's supposed to. This entire code is supposed to perform a form validation check - if the user input is left empty, it should throw an error message. However, when I change the "getElementById" to JQuery $(#);, the form validation doesn't work.

Why does this happen?? Isn't $(#); the exact equivalent of document.getElementById?

Isn't $(#); the exact equivalent of document.getElementById?

Absolutely not, they return very different elements, jQuery returns a

collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.

Jquery() documentation

While document.getElementById() returns

An Element object describing the DOM element object matching the specified ID, or null if no matching element was found in the document.

document.getElementById() documentation

If for compatibility with your previous code you have to access the Element object from the jQuery collection, you can use the array notation.

So if the selector matches a single element, like an id, you can do

let el = $('#selector')[0];

To mimic the behaviour of document.getElementById() .

$("#name") return a jQuery object not an Element object like document.getElementById("pictures"); to return a Element object you need to get the Element object from the jQuery object

$("#name")[0]

如果你想获得#name 的值,那就是

$("#name").val()

$('#fileUpload').val('');

我们必须在 val() 中传递值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM