2

I want to create a variable with the append and HTML function. The reason is when a person clicks on a div he should be replace the element, otherwise he should add the element instead of replace it.

As example, my variable calls: var clicked = true;

My jQuery code looks like this:

// if a user clicks, replace the image
if(clicked == true){
   var type = '.html';
// else (when the page is loading), add the image
}else{
   var type = '.append';
}

// use the var type
container.find('.img') + type + (data.img);

If the image exists he should not add an new one, but he needs te replace him. If he exists he should replace the current image with the new one.

I know, I could do something like this:

if(clicked == true){
   container.find('.img').html(data.img);
}else{
   container.find('.img').append(data.img);
}

But I have a lot of elements, and I think this is a more effective way to write the code.

But is this possible?

2
  • 1
    use each loop if multiple element in container Commented Apr 14, 2017 at 9:17
  • 1
    Yes, I think that @SureshSuthar is right, but to answer to your question we need to see a bit more of your html code. Commented Apr 14, 2017 at 9:23

1 Answer 1

2

When you get the function name as a string, You could try to use Bracket Notation to call that function.

var type = 'html';
container.find('.img')[type](data.img); //same with container.find('.img').html(data.img); 

you could refer more in here

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

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.