I have the following selected text in CKEditor plugin.
monkey needs <span answer="banana">food</span> today
I can retrieve the banana
using the following code
editor.on( 'dialogShow', function( dialogShowEvent )
{
var selection = editor.getSelection();
if (selection) {
var selectedElement = selection.getSelectedElement();
// http://ckeditor.com/forums/Support/GetSelectedElement-returns-null-IE-and-Chrome-BUG
if (selectedElement == null) {
// I have no idea whether this is a correct workaround? Just pray...
selectedElement = selection.getStartElement();
}
if (selectedElement == null) {
return;
}
// Yes :)
var banana = selectedElement.getAttribute('answer');
However, the code will break, if our selected text is
monkey needs <span answer="banana"><strong>food</strong></span> today
May I know what is the correct way to iterate through DOM element of selected text? I expect we have something like getSelectedElements
(Plural). But, I can't find one.
If you want to check all elements starting from selection.getStartElement()
down to editor.editable()
, then you can use the dom.elementPath
.
var elementPath = editor.elementPath();
var answerElement = elementPath.contains( function( el ) {
return el.hasAttribute( 'answer' );
} );
If, on the other hand, you want to traverse the DOM tree in DFS order (source order), then you will want to use the dom.walker
:
var range = sel.getRanges()[ 0 ],
walker = new CKEDITOR.dom.walker( range ),
node;
while ( ( node = walker.next() ) ) {
// .. do something
}
Depending on a case you may want to do dozen of other things, so I can't describe all of them. There's many methods for in the dom.range
class, dom.element
or dom.iterator
.
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.