[Solved] javascript: change color of a single word into a


I think this is what you want:

JavaScript : UPADTE

JSFiddle : DEMO

function mynew() {
    var myDiv = document.getElementById('mydiv');
    var contents = myDiv.innerHTML.split(" ");
    var modText="";

    for (var i = 0; i < contents.length; i++) {
        modText += '<span>' + contents[i] + '</span> ';
    }
    myDiv.innerHTML = modText;

    window.onclick = myFunction;

    function myFunction(e) {
        e.target.className = "change";
        /* STORED IN "SELECTED" VARIABLE */     
        var selected = e.target.innerHTML;
        alert('Selected: ' + selected);
    }
}
span.change {
    color: red;
}
span {
    color:black;
}
<body onload="mynew();">
    <div id="mydiv" class="new">text inside the div</div>
  </body>

JQuery : Previous Post

$(function() {
  var contents = $('#mydiv').text().split(' '),
    modText="";

  for (var i = 0; i < contents.length; i++) {
    modText += '<span>' + contents[i] + '</span> ';
  }

  $('#mydiv').html(modText);

  $('#mydiv').click(function(e) {
    $(e.target).toggleClass('change');
    /* STORING EVERY WORD IN VARIABLE NAMED 'SELECTED' */
    var selected = [];
    $('span.change').each(function() {
      selected.push($(this).text());
    });
    alert('Selected: ' + selected.join(','));
  });
});
span.change {
  color: red;
}
span {
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mydiv">text inside the div</div>

Note: If you do not want to toggle the change of color, then remove toggleClass() and add addClass.

Compatibility : Works on Webkit and Mozilla and IE9+

2

solved javascript: change color of a single word into a