Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding attribute to TinyMCE node with attr not working

I'm developing a WordPress plugin that adds a button to TinyMCE, which lets you add an id attribute to the selected element. I have the button displaying, and when it is clicked it runs my function, which I'll call "idFunc" for this demo and it looks like this:

function idFunc() {

  // Make sure editor has focus.
  editor.focus();

  // Get currently selected node
  var selectednode = editor.selection.getNode();

  // Set the id attribute on the node
  selectednode.attr("id","newid");

}

With idFunc() written as above, nothing happens when I click my button. If I change the last line to an alert like this:

function idFunc() {

  editor.focus();

  var selectednode = editor.selection.getNode();

  // Alert with the selected node
  alert(selectednode);

}

I get an alert as expected, which says:

The page at mytestingdomain.com says: [object HTMLParagraphElement]

If I have my caret in a div instead of a p element, it says:

The page at mytestingdomain.com says: [object HTMLDivElement]

So I know I'm close, but the attr() function isn't adding any attributes to any elements in the TinyMCE editor.

What am I doing wrong?

like image 647
Joe Rhoney Avatar asked Dec 10 '25 19:12

Joe Rhoney


1 Answers

The solution to this is easy. editor.selection.getNode() gives you the common ancestor node (not a jQuery object).

To set the id attribute on the node you may call one of the following commands:

selectednode.setAttribute("id","newid");

or

selectednode.id = "newid";

or using jQuery

$(selectednode).attr("id","newid");
like image 159
Thariama Avatar answered Dec 13 '25 11:12

Thariama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!