0

I am sorry if it is a newbie question, but I have searched alot on internet but couldn't found a solution. Problem is that I want to show a variable value within jquery code, my jquery code is down here,

$(document).ready(function(e) {
    $alt = $('.main-img').attr('alt');
    $('.main-img').after("<div class='slide_title'>$alt</div>");
});

now problem is that I want to show variable alt value in , thnx in advance

3 Answers 3

2

Concatenate variable while creating HTML string.

$('.main-img').after("<div class='slide_title'>" + $alt + "</div>");
Sign up to request clarification or add additional context in comments.

1 Comment

thnx mate for giving your time.
2

The safest way, if the variable's value may include characters like < which are special in HTML, is to use the text function:

$(document).ready(function(e) {
    var main = $('.main-img');
    $("<div class='slide_title'></div>")
        .text(main.attr('alt'))
        .insertAfter(main);
});

If you want to use HTML in the variable's text, then either string concatenation or the html function:

String concat:

$(document).ready(function(e) {
    var main = $('.main-img');
    $("<div class='slide_title'>" + main.attr('alt') + "</div>")
        .insertAfter(main);
});

html:

$(document).ready(function(e) {
    var main = $('.main-img');
    $("<div class='slide_title'></div>")
        .html(main.attr('alt'))
        .insertAfter(main);
});

1 Comment

thanx mate for answering, I got answer from your question but you made it little complex, I need a simple solution like given by Akki619, but still I am very thankful to you.
1

Concat the string properly...

Like this:

$('.main-img').after('<div class="slide_title">' + $alt + '</div>');

or as per Satpal Solution....

it works like

var a = "" + your variable +""

but in your code you have all string

$('.main-img').after('<div class="slide_title"> $alt </div>');

so $alt is considered as string not a variable.

You can put html tag or text or etc which you want before or after your custom variable.

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.