简体   繁体   中英

How do I write this JQuery function in plain JavaScript?

can you please help me to write this function in plain JavaScript in the most efficient way.

//Selects all elements matched by <input> that have a name value 
//exactly equal to myname.
$("input[@name=myname]") 
var els = document.getElementsByTagName("input"),
    arr = [];

for (var i = 0, l = els.length; i < l; i++) {
    if (els.name === "myname") {
        arr.push(els);
    }
}

console.log(arr);

Or for modern browsers:

var arr = document.querySelectorAll("input[name='myname']");
console.log(arr);

这是你想要的:

document.getElementsByName("myname");

Assuming each element in the form has a unique name, this method is the fastest:

var element = document.MyForm.getElementsByName('myname')[0];

document.querySelectorAll() may be faster if name is shared by elements of different tags, but support is limited .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM