0

I'm trying to learn JavaScript, and I wanted to change what I am working on into a pure JavaScript solution. How do I change this to JavaScript:

var hrefs = $("a[id^=a_l_]").map(function() {
  return this.href;
}).get();

It basically finds all id's containing "a_l_" and puts it into an array.

Here is what I have tried

var matches = [];
var elems = document.getElementsByTagName("a");
for (var i=0; i<elems.length; i++) {
  if (elems[i].id.indexOf("a_l_") == 0)
  matches.push(elems[i]);
  console.log(matches);
}
2
  • 1
    @therefromhere sorry forgot my code. i updated post. Commented May 31, 2012 at 9:50
  • on the face of it that code looks OK - what's actually happening with it? Commented May 31, 2012 at 10:04

5 Answers 5

2

Always use brackets {} for conditions! Else soon or later you will make mistakes!

for (var i=0; i<elems.length; i++) {
    if (elems[i].id.indexOf("a_l_") == 0) { // <-- {
        matches.push(elems[i]);
        console.log(matches);
    }                                       // <-- }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could first do a filter, then do a map.

var hrefs = Array.prototype.filter.call(document.getElementsByTagName("a"), function(node) { 
  return node.id.indexOf("a_l_") === 0;
}).map(function(node) {
  return node.href;
});

Comments

0

You are trying to find all elements with id equal "a_l_" and add them to an array. I suggest you shouldn't have the same id for your html elements. You should move them to class. Anyway, try this:

var matches = [];
var elems = document.getElementsByTagName("a");
for(var i=0; i<elems.length; i++) {
  if(elems[i].id.indexOf("a_l_") != -1) {
    matches.push(elems[i]);
    console.log(matches);
  }
}

Comments

0

Assuming ES5 array methods (use a shim / polyfill if they don't exist)

var hrefs = [].filter.call(document.getElementsByTagName('a'), function(el) {
    return el.id.indexOf('a_l_') === 0;
}).map(function(el) {
    return el.href;
});

working demo at http://jsfiddle.net/alnitak/Zu3dJ/

Comments

0

An alternative solution in pure Javascript, working on modern browser (IE8+ included)

var elems = document.querySelectorAll("a[id^='a_l_']");

elems is a collection of <a> elements whose id are starting with a_l_. Indeed querySelectorAll is slower but readability is hugely increased

Comments

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.