简体   繁体   中英

Javascript: Get sibling of current element [needed for CKEditor]

Hey, I am working on a simple Plugin for CKEditor, I am not to firm with JavaScript, so here is my problem.

I upload an image and insert it with a dialog, producing something like this.

<div class="float-right image">  
<img alt="alt-text" src="img.jpg" />   
<span class="caption">Caption</span>  
</div>

Works like a charm, but once i is inserted I want to be able to edit it. Doing so I can get the alt attribute and the src of the image via

var elem = this.getParentEditor().getSelection().getSelectedElement();

and working with getAttribute('...'). But I can not figure out how to reach, the caption and the div.

I would be very happy if you could help me. Thanks in advance.

BTW: Is there a possibility to use jquery within a plugin for CKEditor?

Heres the solution:

So what I came up with in the end, thanks to all the help here. In the dialog part:

onShow : function()
{
elem = this.getParentEditor().getSelection().getSelectedElement();
var span = elem.getNext();
var parent = span.getParent();
}

this gives me all the stuff I need to fill into the dialog once I open it again.

to submit everything I needed to find out how to change the current selection. This works like this:

onOk:
function()
    {
editor.getSelection().selectElement(editor.getSelection().getSelectedElement().getParent());
editor.insertHtml('<div ...</div>');
}

Thank you guys, I only started digging into the CKEditor Plugins today and already I got two nice ones.

通过CKEditor API,您可以使用.getNext()

Yes, you can use jQuery within a CKEditor plugin as long as you don't intend to distribute the plugin (other people may not have jQuery), in which case your solution becomes:

$(elem).next('span') and $(elem).prev('div')

If you don't want to use jQuery, you have .nextSibling and .previousSibling

Note, however, that the next and prev siblings will often be textNodes depending on what browser you're in. So to get the span, you need a loop:

function getNextSibling(node, type){
    while((node = node.nextSibling) && (node.nodeName != type));
    return node;
}

getNextSibling(elem, 'SPAN');

有Element.nextElementSibling,在IE9 +,Fx3.5 +,Op,Saf和Chrome(最近三个版本中都是Dunno版本,但有相当长的一段时间)中受支持。

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