如何在Javascript中选择只知道部分名称的类名
在带有如何在Javascript中选择只知道部分名称的类名,javascript,jquery,class,Javascript,Jquery,Class,在带有editor.selection.getContent()函数的Javascript中,我在wp编辑器中选择图像: <img class="alignnone wp-image-xxx size-large" src="http://....." alt="" /> 但是,我如何在javascript中选择类wp image xxx,而不知道xxx值,以便在替换后能够使用它?以下是适用于您的情况的最基本方法: //Replaces the first class that m
editor.selection.getContent()函数的Javascript中,我在wp编辑器中选择图像:
<img class="alignnone wp-image-xxx size-large" src="http://....." alt="" />
但是,我如何在javascript中选择类wp image xxx
,而不知道xxx
值,以便在替换后能够使用它?以下是适用于您的情况的最基本方法:
//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');
使用substring
手动筛选它们。您可以获得中所述的完整类名,然后可以使用split('-')
,最后一个数组值将是您的ID。如何将jquery选择器应用于编辑器。selection.getContent()?您可以使用regexp jquery选择器$(“:regex(class,.*wp image-*”)
谢谢您的回答。我无法getElementById
,因为img没有ID。我使用editor.selection.getContent()函数获取图像输出:
您需要获取元素,不管您如何获取。可以使用getElementsByTagName('IMG')[0]
,前提是图像是父div中唯一也是第一个IMG
元素,并且如果您有该ID,您可以在父div上运行它,或者以任何其他方式选择它。您需要进一步探索editor.selection提供的内容,“getContent()”不是您需要的。
replaceClass(document.getElementById('foo'), 'wp-image', 'newClassName');