Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
How to make contenteditable div to allow only certain tags?

I'm using a contenteditable div.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div contenteditable="true"></div>

<button id="insert_strong">Strong!</button>

<button id="insert_italic">Italic</button>

<button id="insert_span">Span!</button>

<script>
  $("#insert_strong").click(function(){
      $("div").append('<strong>Strong text!</strong> ');
  });

  $("#insert_italic").click(function(){
      $("div").append('<i>Italic text!</i> ');
  });

  $("#insert_span").click(function(){
      $("div").append('<span>Span text!</span> ');
  });
</script>

Even if I remove the buttons, People can still paste any html tags by copy pasting from any website. I want people to be able to post only <strong> tags inside it, all other tags should be eliminated. How can this be done?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I finally found a solution. Here it is:

$("#insert_strong").click(function(){
    $("div").append('<strong>Strong text!</strong> ');
    div_key_up("div");
});

$("#insert_italic").click(function(){
    $("div").append('<i>Italic text!</i> ');
    div_key_up("div");
});

$("#insert_span").click(function(){
    $("div").append('<span>Span text!</span> ');
    div_key_up("div");
});

function div_key_up(l)
{
  $(l).html(strip_tags($(l).html(), "<strong><br>"));
}

function strip_tags(input, allowed)
{
  allowed = (((allowed || '') + '')
  .toLowerCase()
  .match(/<[a-z][a-z0-9]*>/g) || [])
  .join('');
  var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
  commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
  return input.replace(commentsAndPhpTags, '')
  .replace(tags, function($0, $1)
  {
    return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div contenteditable="true" onkeyup="div_key_up(this);"></div>

<button id="insert_strong">Strong!</button>

<button id="insert_italic">Italic</button>

<button id="insert_span">Span!</button>

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!