wyc
wyc

Reputation: 55263

Add class to selected paragraph (contenteditable div)

I have a series of paragraphs like this in a contenteditable div:

<p>text</p>
<p>text</p>
<p>text</p>

I want to be able to select one of the paragraghs (with the mouse) and add a class to it:

<p>text</p>
<p class="added-class">text</p>
<p>text</p>

What's the simplest way to do this?

(I'm going to create my own event but I want the selected text/paragraph to be the selected element)

Upvotes: 1

Views: 826

Answers (4)

quimet
quimet

Reputation: 23

needn't jQuery:

var ps = document.getElementsByTagName('p');
for (var i = 0; i < ps.length; i++) {
  ps[i].onclick = function(e) { 
    e.target.classList.toggle('click'); 
  };
}

Upvotes: 1

Mr7-itsurdeveloper
Mr7-itsurdeveloper

Reputation: 1631

You Can do this with jquery.simplest and better solution.

Code:

$(function(){

$('p').mouseover(function()
{
$(this).addClass('added-class');

});

});

Example :http://jsfiddle.net/3rfyLpjm/

Upvotes: 0

Rahul K
Rahul K

Reputation: 413

Try it simple using jquery:

HTML

<p>text</p>
<p>text</p>
<p>text</p>

Jquery

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).on('click','p',function(){
    $('p').each(function(){
        $(this).removeClass('added-class');
    });
    $(this).addClass('added-class');
});
</script>

Upvotes: 0

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3645

The simplest solution is:

$("p").on("click", function(){
  $(this).addClass("added-class")
});

If you want to have only one p with "added-class"

var chosen = null;
$("p").on("click", function(){
  if(chosen) 
    chosen.removeClass("added-class");
  $(this).addClass("added-class")
  chosen = $(this);
});

Upvotes: 1

Related Questions