Tips for programmatically choosing a text range within CKEDITOR stages?

Issue:

In my JavaScript code, I have a CKEditor instance like this:

var editor = CKEDITOR.instances["id_corpo"];

I am looking to programmatically insert some text and then select a specific text range within the editor.

So far, I have successfully inserted text using:

editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');

However, my goal is to highlight the word "foobar" using JavaScript so that I can run functional tests with Selenium on my CKEditor plugins.

UPDATE 1:

I attempted the following approach:

var selection = editor.getSelection();
var childs = editor.document.getElementsByTag("p");
selection.selectElement(childs);

Unfortunately, this method did not work as expected!

Is there another way to achieve this?

I believe that utilizing

selection.selectRange()

could potentially solve the issue. However, the lack of examples has made it difficult for me to implement it correctly.

Answer №1

Retrieve current selection

var editor = CKEDITOR.instances["id_corpo"];
var sel = editor.getSelection();

Modify the selection to focus on the current element

var element = sel.getStartElement();
sel.selectElement(element);

Adjust the range to highlight the specific text you want to select

var findString = 'foobar';
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
    ranges[0].setStart(element.getFirst(), startIndex);
    ranges[0].setEnd(element.getFirst(), startIndex + findString.length);
    sel.selectRanges([ranges[0]]);
}

Answer №2

Here are some additional steps you can take:

Retrieve the current selection

var currentSelection = editor.getSelection();
var selectedElement = currentSelection.getSelectedElement();

If no text is currently selected, create a new paragraph element

if (!selectedElement)
    selectedElement = new CKEDITOR.dom.element('p');

Add your content to the element

selectedElement.setHtml(someHtml);

If necessary, add your element to the DOM (it will be placed in the current position)

editor.insertElement(selectedElement);

Finally, select the newly added element

currentSelection.selectElement(selectedElement);

Answer №3

Learn more about the selectElement() function in CKEDITOR.dom.selection.

Explore this link for further details

Answer №4

add new content at the current location in ck editor

  • code to insert variable value: function addContent(myText) { CKEDITOR.instances['editor1'].fire( 'insertElement', myText); }

    this solution is effective for me

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Express: ERROR_HTTP_HEADERS_ALREADY_SENT - It is not possible to set headers once they have already been sent to the client

After reviewing numerous discussions on the same topic, I am struggling to identify where I might be sending the headers initially. The stack trace provided indicates the following: It is concerning that I receive a 204 as it successfully adds to the data ...

Top tips for data manipulation

I am facing an issue with my JavaScript code that makes an ajax request to the server and receives JSON data, which is not correctly formatted for array-based manipulation. A colleague suggested a client-side solution to convert object-based JSON into arra ...

"Design the website with a WYSIWYG editor while preventing users from disrupting the page's

I am considering using an HTML WYSIWYG editor like CKEditor, but I am concerned about the possibility of users submitting HTML code that could alter the layout of the page when rendered. Here is a comparison between two posts: <p><b>This is m ...

Inter-service/module communication on a widget interface

We are in the process of creating a widget screen that contains various widgets/modules: Products: Displays a list of products Product Details: Retrieves product details from the server when a selection is made in the "Products" widget. Related Products: ...

Sending JSON data containing an IFormFile and a string as parameters to C#

Software Versions: ASP.NET and Web Tools - 17.10.341.11210 C# Tools - 4.10.0-3.24312.19+ JQuery - 3.3.1.js JS - 2.8.3.js Currently, I am attempting to pass an IFormFile and a string from a JSON file select and a string input. After thorough testing, I ha ...

Tips for effectively managing state in React applications

Upon clicking submit, I am looking to retrieve either a '+' or '-' result. However, I'm unsure of how to handle this within my code. Below is the code snippet along with the current result before 'submit' is clicked. c ...

Enhance PHP search functionality by showcasing hidden auto-complete suggestions in real-time

I am attempting to showcase unlisted search results that can be clicked on to redirect the user to a specific HTML page based on data retrieved from a MySQL database. My development environment is PhoneGap. Thus far, I have successfully set up a basic PH ...

Instructions on installing chromedriver tailored to the specific version of the locally installed Chrome browser using Python in Selenium

Looking to get the chromedriver that matches the current version of the local chrome browser during runtime. The code should operate as follows: 1. Check the version of the chrome browser. 2. Install the chromedriver that corresponds to that specific chro ...

Utilizing Tables and Dates to Present Data in a Chart

In order to display my data from the database in a chart, I am utilizing Google Chart. The issue arises when I attempt to count and join tables; if the date from two different tables does not match, the data will not appear. For instance, consider the fo ...

Exploring the depths of JSON using @attributes and @association in the realm of JavaScript and AngularJS

Currently, I am working on a project that involves utilizing an API for data retrieval, updates, and deletions. The API in question is the prestashop API. While I have managed to retrieve data and update certain items successfully, I encountered an issue. ...

Difficulty with subdomain rendering in ExpressJS

Currently, I am working on my store and facing an issue with rendering. Everything is fine for the route /category, as shown below: const CategoryOne = ((req, res) =>{ res.render('shop/category'); }); router.get('/category', Cate ...

What is the best way to use Python and Selenium to upload a batch of images on Instagram?

Currently, I am developing an Instagram bot and looking for a way to automate picture uploads using selenium. While emulating a phone in my selenium setup, I face the issue where Explorer insists on manually selecting pictures whenever I click on the upl ...

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...

Creating Dynamic Popover Content with Bootstrap 5 Using an Asynchronous Function

Trying to create a bootstrap 5 popover with dynamic content by using an asynchronous function has been quite a challenge. Here is how I am setting up my popover: document.querySelectorAll('[data-bs-toggle="popover"]').forEach(function ( ...

The functionality of ng-disabled in AngularJS is not functioning properly

This form is not behaving as expected. <form name="myForm"> <input ng-disabled="true" type="text" >* </form> I can't figure out why the input field is not disabled as intended. I even tried using $scope in the controller: $scope.d ...

What is the Placement of Grant_Type in XHR?

I attempted to access my OAuth2 Token through an XHR-Request in TypeScript, but I consistently receive a 400 error with the message: {"error":"unsupported_grant_type","error_description":"Grant Type is NULL"} The request is being made from a NativeScript ...

What is the best way to avoid having identical entries in a row when using jQuery's multiple select feature?

I am facing the challenge of working with multiple rows containing select boxes that have similar content. Each row has several select boxes and each item in a row can only be used once due to specific classifications assigned to each column. I want the se ...

Empty space on the edge of the mobile screen in Next.js causes usability issues

Currently working on a frontend project using Next.js and Tailwind. Encountered an issue where there is extra space on screens with a width less than 500px. For instance, if the screen width is 400px, there will be an additional 100px of deadspace. Simila ...

jQuery tabs with carousel navigation

I am looking to enhance my jQuery tabs with a prev/next navigation in the form of a carousel. However, I am unsure of how to go about implementing this feature. Here is a snippet of my current code: Javascript <script type="text/javascript> ...

Jquery animation in Wordpress without any need for scrolling

My Wordpress site features some animations that work flawlessly when the site is scrolled. The code looks like this: jQuery(document).ready(function($){ $(window).scroll( function(){ if(!isMobile) { $('.animate_1').each ...