i use such code to access item
function f(id){
$(\"#\"+id).val(); // with analogy $(\"#id item\")
}
is it correct? is any other methods?<
You could use PureDom
function f(id){
return document.getElementById(id).value;
}
Take that, jQuery!
If you want to return the value of an element with specified id, then yes as that is what seems to be logical purpose of your function:
function f(id){
return $("#" + id).val();
}
The functions should assume that an element with specified id exists and then it returns you the value of that element. This should work for input
fields as well as textarea
. If however, it is any other element, you might want to use html()
or text()
instead of val()
eg:
function f(id){
return $("#" + id).html();
// return $("#" + id).text();
}
From the jQuery API website:
.val() Returns: String, Array
Description: Get the current value of the first element in the set of matched elements.
What It's not clear to me when you say
// with analogy $("#id item")
is if you want to have ONLY one child item of the one that is identifiedby #id or if you need the item that is identified by item#id.
Your code is perfect if you are passing a string like "hello" inside your code and you want to get the DOM element with ID of #hello.
Yes this is perfectly valid way to access the element having its id.