简体   繁体   English

如何选择只知道Java语言中一部分名称的类名称

[英]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.

相关问题 javascript修改css类属性,同时只知道类的名称 - javascript modify css class property while knowing only the class' name 当它不是应用于元素的唯一类时,通过知道其名称的一部分来获取类名称 - Get a class name by knowing part of it's name when it's not the only class applied to an element 选择一个属于零件名称和零件变量的类 - Select a class which is part name and part variable 如何仅从javascript文档的一部分中按类名获取元素? - How to get elements by class name only from one part of the document in javascript? 如何通过 JavaScript 的 class 名称来 select 偶数元素? - How to select even elements by class name with JavaScript? 有没有办法在不知道其类名或ID的情况下选择父div? - Is there a way to select parent div without knowing its class name or ID ? 如何使用JavaScript更改div类名称的一部分 - How to change a part of a div class name using JavaScript 通过类名称的PART来获取元素[JavaScript] - Get element by PART of class name [JavaScript] 如何通过与多个类名匹配的类名选择javascript中的元素? - How to select elements in javascript by class name matching with multiple class names ? 如何包含仅知道名称而不知道扩展名的图像文件? - how to include an image file knowing only name and not extension?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM