1

In Javascript with editor.selection.getContent() function i get the image selected in the wp editor:

<img class="alignnone wp-image-xxx size-large" src="http://....." alt="" />

i need to select the class wp-image-xxx and replace it with a class that include a new id (xxx).

With classList i can get all classes:

var imgselected = editor.selection.getNode();
var classes = imgselected.classList;

But how can i select in javascript the class wp-image-xxx without knowing the xxx value so to be able after to replace it?

Phill Healey
  • 3,084
  • 2
  • 33
  • 67

1 Answers1

0

Here is the most basic way that is applicable in your case:

//Replaces the first class that matches the name given as its "start" of string with a new class name;
function replaceClass(element, searchClassName, replacementClassName) {
  element.classList.remove(findClassName(document.getElementById('foo'), searchClassName));
  element.classList.add(replacementClassName)

  //used to find a className
  function findClassName(element, searchPhrase) {
    var classNameFound = "";
    element.classList.forEach(function(className) {
      if (className.substring(0, searchPhrase.length) === searchPhrase) {
        //Element found
        if (!classNameFound)
          classNameFound = className;
      }
    });
    return classNameFound;
  }
}

just run it with something like:

replaceClass(document.getElementById('foo'), 'wp-image', 'newClassName');
Dellirium
  • 1,362
  • 16
  • 30
  • Thank you for answer. I can't `getElementById` because img doesn't have an ID. I get image output with editor.selection.getContent() function: `` – Gaspare Messina Jun 08 '17 at 12:07
  • you need to get the element, however way you can. Can use `getElementsByTagName('IMG')[0]` providing the image is the only and first `img` element in the parent div and that you run this on the parent if you have that ID, or select it in any other way. – Dellirium Jun 08 '17 at 12:10
  • You need to further explore what editor.selection offers, "getContent()" is not what you need. – Dellirium Jun 08 '17 at 12:31