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:

Read More
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?

Related posts

1 comment

  1. 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");
    

Comments are closed.