Append a Space with jQuery

Append a Space with jQuery

I'm trying to append a space using jQuery. Neither of these samples work:

  $("#mySelector").append($(" "));
  $("#mySelector").append($(" "));

Any ideas?

0

5 Answers

How about

$("#mySelector").append(" "); // or with & nbsp;
0

In my case I did the following:

$('.colwid10a').each(function () {
    if ($(this).is(':empty')) {
        $(this).append(" ");
    }
});
$('.colwid12').each(function () {
    if ($(this).find('a').is(':empty')) {
        $(this).find('a').append(" ");
    }
});

You could also use '\xa0', it is a non break space character.

$("#mySelector").append('\xa0');

And, create a JQuery Plugin function to reuse it whenever you need to put space. This way you will be consistent throughout.

if(!$.space) {
        $.space = function​(noOfSpaces) {
            var space = " ", returnValue = "";
            for(var index=0; index < noOfSpaces; index++) {
                returnValue += space;
            }
            return returnValue;
        }
    }

alert("Stack" + $.space(6) + "Overflow");
1

Untested (and probably a bit overkill):

$("").append($("<p> </p>").text());
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.