admin管理员组

文章数量:1417057

I am iterating over some elements and I have found that document.getElementById("id") works, but $("#id") does not. Why?

Edit: I suppose it wouldn't hurt to post code?

function myFunction() {
    var token, tokens, id, input;
    $("[id^=\"some_id_\"]").each(function() {
        tokens = this.id.split("_");
        id = tokens[tokens.length - 1];
        input = document.getElementById("some_form_element_" + id);  //WORKS
        //input = $("#some_form_element_" + id); //DOESNT, alerts undefined

        alert(input.value);
    });
}

I am iterating over some elements and I have found that document.getElementById("id") works, but $("#id") does not. Why?

Edit: I suppose it wouldn't hurt to post code?

function myFunction() {
    var token, tokens, id, input;
    $("[id^=\"some_id_\"]").each(function() {
        tokens = this.id.split("_");
        id = tokens[tokens.length - 1];
        input = document.getElementById("some_form_element_" + id);  //WORKS
        //input = $("#some_form_element_" + id); //DOESNT, alerts undefined

        alert(input.value);
    });
}
Share Improve this question edited Mar 16, 2012 at 15:11 Tyler asked Mar 13, 2012 at 19:26 TylerTyler 20k21 gold badges102 silver badges158 bronze badges 7
  • 8 What does your code look like? Have you included jQuery? Get any JS-errors? – Christofer Eliasson Commented Mar 13, 2012 at 19:27
  • 1 What happens? what is the error displayed? – jackJoe Commented Mar 13, 2012 at 19:28
  • maybe you have multiple elements with the same id – Ibu Commented Mar 13, 2012 at 19:28
  • Did you properly escape the ID in the selector case? – pimvdb Commented Mar 13, 2012 at 19:29
  • 1 is the element you are trying to call already in you DOM? is this called in the window.load or the document.ready function? – arvidkahl Commented Mar 13, 2012 at 19:31
 |  Show 2 more ments

2 Answers 2

Reset to default 6

You are alerting input.value, value is not defined on the jQuery wrapper object.

document.getElementById will directly return a DOM element. But $() returns a jQuery object that wraps the DOM element. You can get at the input's value in the jQuery case with $('#someId').attr('value'); or $('#someId').val()

Here is a fiddle that demonstrates: http://jsfiddle/CK2xr/

It's probably the case that you're:

  1. Testing in IE and
  2. Using a "name" attribute instead of "id".

Internet Explorer (at least, the older versions) return elements when the "name" attribute matches the "id" you're looking for, in one of the more absurd API idiocies those browsers perpetuate.

edit — to clarify: Internet Explorer's document.getElementById() function will match on the "id" attribute or the "name" attribute, and it returns the first one it finds in the DOM. The jQuery API tries to actually satisfy the semantics of the "#" selector syntax, which — even in IE — only matches "id" attributes.

本文标签: