Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating TinyMCE content with jQuery

With TinyMCE, I can easily manipulate content and send it back to the editor, like this:

    // get content from tinyMCE
    var content = tinyMCE.get('content').getContent();

    // manipulate content using js replace
    content = content.replace(/<\/?div>/gi, '');

    // send back to tinyMCE
    tinyMCE.get('content').setContent( content );

The above code works fine. However, I can't get this to work:

    // get content from tinyMCE (it provides an html string)
    var content = tinyMCE.get('content').getContent();

    // make it into a jQuery object
    var $content = $(content);

    // manipulate the jquery object using jquery
    $content = $content.remove('a');

    // use a chained function to get its outerHTML
    content = $("<div />").append( $content.clone() ).html();               

    // send back to tinyMCE
    tinyMCE.get('content').setContent( content );

Is there something wrong with my methodology?

like image 842
supertrue Avatar asked Jan 11 '12 23:01

supertrue


2 Answers

The setting and getting to TinyMCE was correct; the problem was with my use of .remove():

$content = $content.remove('a');

Since the content from TinyMCE was a single object, and not a collection of objects some of which were <a> tags, that manipulation had no effect, and the html that returned was the same as the original.

In order to remove links, I instead needed this:

$content = $content.find('a').remove();

I received clarification in this thread: Difference between $('#foo').remove('a') and $('#foo').find('a').remove()

like image 179
supertrue Avatar answered Sep 19 '22 13:09

supertrue


You need to get the editor content using

var content = $('#content').html();

and set the content using

var content = $('#content').html('<span>NEW CONTENT</span>');
like image 24
Thariama Avatar answered Sep 19 '22 13:09

Thariama