在具有editor.selection.getContent()
功能的Javascript中,我获得了在wp编辑器中选择的图像:
<img class="alignnone wp-image-xxx size-large" src="http://....." alt="" />
我需要选择类wp-image-xxx
并将其替换为包含新id(xxx)的类。
使用classList,我可以获得所有类:
var imgselected = editor.selection.getNode();
var classes = imgselected.classList;
但是如何在不知道wp-image-xxx
值的情况下在javascript中选择xxx
类,以便能够在替换它之后呢?
答案 0 :(得分:0)
以下是适合您案例的最基本方式:
//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;
}
}
只需运行以下内容:
replaceClass(document.getElementById('foo'), 'wp-image', 'newClassName');