最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to change a span label's class using Javascript - Stack Overflow

programmeradmin6浏览0评论

I have an html element like this:

<dd><span class="label label-success" id="status">Production</span></dd>

I want to change it to

<dd><span class="label label-warning" id="status">Idle</span>

based on a ws.socket message.

setTimeout(function(){
            window.ws = new WebSocket('ws://localhost:8088/sock/123');
            window.ws.onmessage = function (evt) {
                field.value = "Idle"
            };
            window.ws.onclose = function (evt){

            }
            window.ws.onopen = function (evt){

            }

        }, 500);

I want to change the value from Production to Idle and the class to "label label-warning". I know to change the value I would do this:

var field = document.getElementById("status")

but I'm not exactly sure how to change the class and would using field.value be the correct way to change a span text?

I have an html element like this:

<dd><span class="label label-success" id="status">Production</span></dd>

I want to change it to

<dd><span class="label label-warning" id="status">Idle</span>

based on a ws.socket message.

setTimeout(function(){
            window.ws = new WebSocket('ws://localhost:8088/sock/123');
            window.ws.onmessage = function (evt) {
                field.value = "Idle"
            };
            window.ws.onclose = function (evt){

            }
            window.ws.onopen = function (evt){

            }

        }, 500);

I want to change the value from Production to Idle and the class to "label label-warning". I know to change the value I would do this:

var field = document.getElementById("status")

but I'm not exactly sure how to change the class and would using field.value be the correct way to change a span text?

Share Improve this question asked Apr 10, 2014 at 15:43 user2769651user2769651 1711 gold badge3 silver badges15 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

You have jQuery, use it!

$("#status").text("Idle").removeClass("label-success").addClass("label-warning");

Or just .toggleClass("label-success label-warning");

Use Jquery

Try this

$('#status').text('Your Text')  //For setting text
$('#status').removeClass('label-success').addClass('label-warning')

If you are just wanting to use JavaScript and not jQuery, you can refer to this answer. You can easily set the class by just saying:

document.getElementById("whatever").className = "";

To change the class (this is much more convenient using jQuery):

document.getElementsById('status').setAttribute("class","label label-warning");

To change the value of the span text:

document.getElementsById('status').innerHTML = "Production";
发布评论

评论列表(0)

  1. 暂无评论