【问题标题】:How to select a class name knowing only a part of name in Javascript如何在Javascript中选择只知道部分名称的类名
【发布时间】:2023-03-22 22:15:01
【问题描述】:

在带有 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;

但是我如何在 javascript 中选择 wp-image-xxx 类而不知道 xxx 值以便能够在之后替换它?

【问题讨论】:

  • 使用substring手动过滤它们
  • 你可以得到this answer中所说的完整类名,然后你可以使用split('-'),最后一个数组值就是你的ID。
  • 如何将 jquery 选择器应用到 editor.selection.getContent()?
  • 可以使用正则表达式 jquery 选择器$(":regex(class, .*wp-image-.*)")

标签: javascript jquery class


【解决方案1】:

这是适用于您的情况的最基本方法:

//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');

【讨论】:

  • 感谢您的回答。我不能getElementById 因为img 没有ID。我使用 editor.selection.getContent() 函数获得图像输出:&lt;img class="alignnone wp-image-xxx size-large" src="http://....." alt="" /&gt;
  • 你需要获取元素,但是你可以。可以使用 getElementsByTagName('IMG')[0] 提供图像是父 div 中唯一且第一个 img 元素,并且如果您有该 ID,您可以在父 div 上运行它,或者以任何其他方式选择它。
  • 你需要进一步探索 editor.selection 提供什么,“getContent()”不是你需要的。
猜你喜欢
  • 2012-08-09
  • 2017-11-24
  • 1970-01-01
  • 2012-10-16
  • 1970-01-01
  • 2011-02-11
  • 1970-01-01
  • 2022-08-24
  • 2015-10-04
相关资源
最近更新 更多