1

I want to display an image but with code like this:

HTML:

<a href="javascript:" class="menuin" from="account.png"></a>
<a href="javascript:" class="menuin" from="home.png"></a>

Jquery:

$(".menuin").html('<img src="img/'+$(this).attr('from')+'">');

I have a trouble on jquery code. I think that is wrong code. I want to display an image according to from attribute. can you help me please?

1
  • .html takes a callback function as it's parameter - see @Satpal's answer below Commented Dec 10, 2018 at 6:48

1 Answer 1

3

You should use .html(function) method, it will iterate .menuin elements and use current element context i.e. this to get the relevant attribute value.

I would also recommend to use data-* prefixed custom attributes.

$(".menuin").html(function(index, oldHtml) {
  return '<img src="img/' + $(this).data('from') + '">'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="javascript:" class="menuin" data-from="account.png"></a>
<a href="javascript:" class="menuin" data-from="home.png"></a>

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.