1

I am trying to loop through an array of elements and then validate each instance of each element. This is how I am doing it:

var elements = ["h1","h2","h3","h4","p","strong","label","span","a"];
function targetZWS(){
    for (var i = 0; i < elements.length; i++) {
        var item = $(".page-content "+elements[i]);
        $(item).each(function() {
            checkElement(this);
        });
    }
}

This throws a warning that I am creating a function inside a loop, how do I avoid this?

2
  • would making a checkElements function that loops over all of your items and calling it from inside the loop still cause a warning? Commented Apr 19, 2016 at 17:29
  • JavaScript doesn't have such a warning. You must be using a linter. You might be able to configure the linter to ignore that line. Or get rid of the loop by changing your code to $(".page-content").find(elements.join(',')).each(...). Or change checkElement to accept an index as first argument and the element as second argument and use item.each(checkElement). Or both. Commented Apr 19, 2016 at 17:29

2 Answers 2

1

You are trying too hard :) JQuery allows you to enter multiple options in a single selector.

function targetZWS(){
    $("h1,h2,h3,h4,p,strong,label,span,a").each(function() {
            checkElement(this);
        });
    }
}

http://api.jquery.com/multiple-selector/

Sign up to request clarification or add additional context in comments.

Comments

0

Use .each() to loop through the array as:

 $(function() {
  var elements = ["h1","h2","h3","h4","p","strong","label","span","a"];
  $.each(elements, function(index, value) {
    alert(value);
    var sel = ".page-content" + value
    var item = $("sel");
        $(item).each(function() {
            checkElement(this);
        });
  })
})

DEMO

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.