Tyler
Tyler

Reputation: 19848

document.getElementById("id") works, but $("#id") does not jQuery

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);
    });
}

Upvotes: 1

Views: 2633

Answers (2)

Matt Greer
Matt Greer

Reputation: 62027

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.net/CK2xr/

Upvotes: 6

Pointy
Pointy

Reputation: 413682

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.

Upvotes: 2

Related Questions