[英]How to select a class name knowing only a part of name in Javascript
In Javascript with editor.selection.getContent()
function i get the image selected in the wp editor: 在带有editor.selection.getContent()
函数的Javascript中,我获取了在wp编辑器中选择的图像:
<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). 我需要选择类wp-image-xxx
并将其替换为包含新ID(xxx)的类。
With classList i can get all classes: 使用classList我可以获取所有类:
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? 但是我如何在JavaScript中选择类wp-image-xxx
而又不知道xxx
值,以便能够在以后替换它?
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.