简体   繁体   中英

Newly added DOM element returns null

I am adding a span to a tinymce document at run time.

ed.onKeyUp.add(function (ed, e) {
   sendText(ed, e);
   ed = tinyMCE.get('editor');
   range = ed.selection.getRng();

   var newNode = ed.getDoc().createElement("span");
   newNode.id = "caret";
   ed.getDoc().body.appendChild(newNode);

   newNode.innerHTML = "|";
   newNode.style.color = "black";
   range.insertNode(newNode);
});

As you can see I am adding the node by using the createElement method and also adding it to the DOM by using append child to my desired element.

The problem is that I can't find the newly added element by using:

document.getElementById("caret");

It is returning null. Why is this happening? Any idea what I can do?

EDIT : I am using document.getElementById("caret"); in a function which I call upon initializing the tinyMCE document since I need this function for blinking a custom caret.

This is the function:

function blink() {
        var caret = document.getElementById("caret");

        if (caret.style.color == "transparent") {
            caret.style.color = "black"
        } else {
            caret.style.color = "transparent";
        }
    }

and I'm calling it oninit: setInterval("blink()", 700) where oninit is a parameter for tinyMCE.

TinyMCE uses an iframe containing its own document to allow editing.

As such, when you use document.getElementById , you're searching the wrong DOM.

If you have access to the TinyMCE editor object, you could use ed.getDoc().getElementById() instead.

If you need global access, you can use the TinyMCE.editors collections to access the specific editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM