简体   繁体   中英

Unable to change Span text using JQuery

I am using bootstrap and JQuery.

HTML

<div>
    <ul>
       <li><strong> Status : </strong><span id="monitorStatusSpan">1111</span></li>
    </ul>           
</div>

<button type="button" id="disableButton"
                    class="btn btn-primary" onclick="changeSpan();">Change</button>

JavaScript

function changeSpan() {
 $('#monitorStatusSpan span').text('disssssssssssssssssss');   
}

Here is the fiddle. http://jsfiddle.net/alamzeeshan/5bw8d2ta/7/

But still the span text is not getting changed.

Does anyone know what am I missing?

Currently, you're looking for a span inside your #monitorStatusSpan ( #monitorStatusSpan span ).

function changeSpan() {
    $('#monitorStatusSpan span').text('disssssssssssssssssss');   
}

It's enough to only look for the ID like this:

function changeSpan() {
    $('#monitorStatusSpan').text('Your text here');   
}

You have incorrect selector. Selector you have used finds #monitorStatusSpan element and then span element in it. which do not exist.

As IDs are unique, you can simply use id selector to target the required element:

function changeSpan() {
 $('#monitorStatusSpan').text('disssssssssssssssssss');   
} 

working demo

HTML

<div>
    <ul>
        <li><strong> Status : </strong><span id="monitorStatusSpan">1111</span></li>
    </ul>           
</div>

<button id="disableMonitorButton" class="btn btn-primary">Change</button>

JS

$("#disableMonitorButton").click(function() {
    $('#monitorStatusSpan').html('disssssssssssssssssss');  
});

PS. DONT USE inline JS!

Try this

 function changeSpan() { $('#monitorStatusSpan').text('disssssssssssssssssss'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <ul> <li><strong> Status : </strong><span id="monitorStatusSpan">1111</span></li> </ul> </div> <button type="button" id="disableButton" class="btn btn-primary" onclick="changeSpan();">Change</button> 

Your current selector selects all span 's inside element with id #monitorStatusSpan but in this element there are not any span's .

For your current selector html should look like this

<span id="monitorStatusSpan"><span>TEST</span></span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM