Jquery dynamic id

I use this code to access an element

function f(id){ $("#"+id).val(); // with analogy $("#id item") } 

Is it correct? any other methods?

+4
source share
4 answers

If you want to return the value of the element with the specified id, then yes, since this is what seems to be the logical goal of your function:

 function f(id){ return $("#" + id).val(); } 

Functions should assume that there is an element with the specified identifier, and then it returns the value of this element. This should work for input fields as well as textarea . If, however, this is any other element, you can use html() or text() instead of val() for example:

 function f(id){ return $("#" + id).html(); // return $("#" + id).text(); } 
+4
source

You can use PureDom

 function f(id){ return document.getElementById(id).value; } 

Take it, jQuery!

+1
source

Yes, this is a perfectly acceptable way to access an element with its own identifier.

0
source

On the jQuery API website:

.val () Returns: String, Array

Description: Get the current value of the first element in the set of matched elements.

What I don’t understand when you say

// with the analogy of $ ("# id item")

if you want ONLY one child of the one identified by #id, or if you need an element identified by # id.

Your code is ideal if you pass a string like " hello " inside your code, and you want to get a DOM element with the identifier #hello .. p>

0
source

Source: https://habr.com/ru/post/1310714/


All Articles