Javascript DOM How to - Create new text span element and apply style








Question

We would like to know how to create new text span element and apply style.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.10.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--   www  . j a  v a 2  s.  c  o m-->
    var addedElement = $('<span>HelloWorld</span>');
    addedElement.css('color', 'Red').css('font-weight', 'bold');
    $("#box").append(addedElement);
});
</script>
</head>
<body>
  <div id="box">existing text:</div>
</body>
</html>

The code above is rendered as follows: