Reputation: 279
I would like to add some text inside a span if it is empty.
The span below DOES contain text, so it should do nothing.
<span class="content">This span has text so do nothing</span>
The span below does not contain any text, so I want the Javascript to automatically add text into the span for me, I want it display "Public".
<span class="content"></span>
So the final result for the above example will be
<span class="content">Public</span>
Upvotes: 1
Views: 2390
Reputation: 177
Using Pure JavaScript:
function myFunction() {
var x = document.getElementsByClassName("content");
for(i=0;i<x.length;i++)
{
if(x[i].innerHTML=="")
{
x[i].innerHTML = "Public";
}
}
}
Here is the fiddle: http://jsfiddle.net/7fet87rb/
Upvotes: 0
Reputation: 177691
You can try the :empty selector
For example
$("span.content:empty")
.text("Public")
Upvotes: 2
Reputation: 186
in jQuery
$span = $(".span");
if($span.text() == ""){
$span.text("Public");
}
Here you can see Example - JSFIDDLE - http://jsfiddle.net/3vcL2e97/
Upvotes: 1
Reputation: 115212
You can use html()
or text()
with callback function
$('span.content').html(function(i, v) {
return v.trim() == '' ? 'public' : v;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="content">This span has text so do nothing</span>
<span class="content"></span>
Upvotes: 1