1

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]") 
6
  • 2
    There isn't really an "efficient" way to do this in Javascript other than using the exact same method jQuery is using. jQuery has done a lot of work on making these selectors extremely efficient. Is there a reason you can't use jQuery, or is this just an academic exercise? Commented Jan 12, 2013 at 0:54
  • No it's not an academic exercise, I'm using JavaScript in my program, and to evaluate JQuery every time I load the page is not good at all.. Commented Jan 12, 2013 at 0:57
  • 1
    Ok? But a lot of existing web sites do that - successfully ;) Even stackoverflow. Commented Jan 12, 2013 at 0:57
  • Most (read:every) modern browser caches javascript, so it will not "load" jQuery every time you load the page. Commented Jan 12, 2013 at 0:58
  • Especially if you load it from google, like many sites do. Just look at the source of stackoverflow. Think about it, who doesn't have Google in his or her browser's cache - maybe 0.2% of the whole internet? Commented Jan 12, 2013 at 1:01

3 Answers 3

5
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);
Sign up to request clarification or add additional context in comments.

3 Comments

Great thank you very much! the second approach looks very nice and clean
@Vor However it is not supported by IE < 8.
That's fine, as long as webkit support it =)
4

Is this what you are looking for:

document.getElementsByName("myname");

1 Comment

No, it's not, It's just an example, I wouldn't use 'name' in real program
3

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 .

1 Comment

Sorry, If my question is not clear enough, but 'name' was just an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.