0

I'm working on a project where I have different sets of div like heading, text, image etc..

Upon clicking I want to append input boxes for that relevant numbers of divs.

You can see working fiddle here : http://jsfiddle.net/UN62E/

This script does a job for me but I need improvement with this script.

This is how part of my script look like :

var eltofind = "heading";

if($(this).find("." + eltofind).length != 0){

    var eltoget = $(this).find("." + eltofind);

    $(eltoget).each( function(index) {
         var item = $('input.' + eltofind + ':first').clone();
        var count = (index +1);
        var getting = eltofind + "-" + count;
        item.addClass(getting);
        item.appendTo('#input');
    });
}

Currently I'm repeating whole script for individual sets of div. Is there a way to call all sets of divs within array? for example :

var eltofind = ["heading", "text", "image"] 

& call them within each function ?

My jQuery skills aren't that good & Any help would be appreciated.

3 Answers 3

3

You can make multiple selectors in jQuery

$(".heading, .text, .image").foo();
Sign up to request clarification or add additional context in comments.

Comments

1

Just run $.each() on the array an replace eltofind with the el argument:

var elstofind = ["heading", "text", "image"];

$.each(elstofind, function(i, el){

    if($(this).find("." + el).length != 0){
        var eltoget = $(this).find("." + el);

        $(eltoget).each(function(index) {
            var item = $('input.' + el + ':first').clone();
            var count = (index + 1);
            var getting = el + "-" + count;
            item.addClass(getting);
            item.appendTo('#input');
        });
    }

});

Comments

0

Create a loop that loops through each value of eltofind and performs the appropriate actions.

var eltofind = ["heading", "text", "image"];

for(var i=0; i < eltofind.length; i++){
     var thisElement = eltofind[i];

    if($(this).find("." + thisElement).length != 0){

        var eltoget = $(this).find("." + thisElement);

        $(eltoget).each( function(index) {
            var item = $('input.' + thisElement + ':first').clone();
            var count = (index +1);
            var getting = thisElement + "-" + count;
            item.addClass(getting);
            item.appendTo('#input');
        });
    }
}

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.