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);
});
}
You are alerting
input.value,valueis not defined on the jQuery wrapper object.document.getElementByIdwill 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/