如何选择一个只知道Javascript中名称的一部分的类名

时间:2017-06-08 10:04:00

标签: javascript jquery class

在具有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类,以便能够在替换它之后呢?

1 个答案:

答案 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');