Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

html - How to change the text of a <span> element using Javascript without <span> disappearing?

I have a really simple question but it's something I have not done before.

I have <span>↑</span> in my HTML:

<div class="button--up-down" data-type="up">
    <span>↑</span>
</div>

But I dont have <span>↑</span> in my JS:

var lastPageScroll = 0;
$(document).on('click', '.button--up-down', function () {
    var type = $(this).attr('data-type');
    var speed = 0; //ms

    if (type == 'up') {
        lastPageScroll = $("body,html").scrollTop();
        if (lastPageScroll > 0) $(this).attr('data-type', 'down').text('↓');
        $("body,html").animate({
            scrollTop: 0
        }, speed);
    }
    if (type == 'down') {
        $(this).attr('data-type', 'up').text('↑');
        $("body,html").animate({
            scrollTop: lastPageScroll
        }, speed);
    }
});
$(document).on('scroll', function () {
    var $button_up_down = $('.button--up-down');
    var type = $button_up_down.attr('data-type');

    if ($(window).scrollTop() > 150) {
        $button_up_down.addClass("visible");

        if (type == 'down') {
            $button_up_down.attr('data-type', 'up').text('↑');
        }
    } else if (lastPageScroll == 0 || ($button_up_down.attr('data-type') == 'up' && $(window).scrollTop() < 150)) $button_up_down.removeClass("visible");
});

So I need to add <span>↑</span> to my JS but i am not sure how to add it without using innerHTML?

Sorry for the noob question.

question from:https://stackoverflow.com/questions/65950102/how-to-change-the-text-of-a-span-element-using-javascript-without-span-disap

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

//create any element gave it an id

<div id="app"></div>

// this line of code write in onCick handler

let app = document.querySelector('#app');
app.append('<span></span>');

//use templating string if you want to set any value in span like this

app.append(`<span>${anyValue}</span>`);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...