【问题标题】:How to get a list of class names from html code? [duplicate]如何从 html 代码中获取类名列表? [复制]
【发布时间】:2014-11-26 09:47:38
【问题描述】:

有一个 javascript 字符串是有效的 html 代码。 获取包含从该字符串中抓取的所有类的 javascript 数组的最快方法是什么?

var mystr = '<div class="class1 class2"><p id="id1">some <span class="class3">text about class="class4"</span></p></div>';

预期的结果是

var myarr =  ["class1","class2","class3"];

请仅使用唯一的类。这个数组中的顺序无关紧要。

【问题讨论】:

  • 这将比您想象的更麻烦。无论如何,该字符串不是有效的 JS 字符串。您将不得不转义内部引号,或者对字符串本身使用单引号。
  • @Cerbus。抱歉,将一些 " 更改为 '。

标签: javascript arrays regex string substring


【解决方案1】:

以上这些方法对于这个问题来说似乎太复杂了。我认为您不必将字符串附加到文档中。我只需将字符串用子字符串 'class="' 分开,然后从那里开始工作。

var tags = mystr.split("class=\"");
var classes = new Array();
var endclass;
for (var i=0; i<tags.length; i++) {
  endclass = tags[i].indexOf("\">");
  if (endclass > -1) {
    var newclass = tags[i].substring(0,endclass).split(" ");
    classes = classes.concat(newclass);
  }
}

这是我的 jsfiddle:http://jsfiddle.net/nmkjvqmL/

然而,这是假设类位于标签的末尾。如果它并不总是在标签的末尾,您可以更改此行:endclass = tags[i].indexOf("\"&gt;"); 到此 endclass = tags[i].indexOf("\""); 但是,这将包括不在标签中的字符串 class="whatever",因此您必须使确保此文本不在字符串中。

【讨论】:

    【解决方案2】:

    你可以这样做:

    var div = document.createElement('div'), //Create a "container" for the html
        elements, classes = [];
    // Insert the HTML into the container, allowing the browser to parse it's DOM
    div.innerHTML = '<div class="class1 class2"><p id="id1">some <span class="class3">text about class="class4"</span></p></div>'  then.
    var elements = div.querySelectorAll('*'); // Get an array of all elements
    
    for(var i = 0; i < elements.length; i++){
        classes = classes.concat(elements[i].className.split(' ')) // Concat an array of classnames for each element in there.
    }
    
    classes = classes.filter(function(element){return element !== ''}) // Filter out empty class names.
    
    console.log(classes)
    alert(JSON.stringify(classes))

    请注意,这会同时使用:
    forEachquerySelectorAll,它们都仅从 IE 9 开始完全支持。

    【讨论】:

      【解决方案3】:

      一种方法,避免使用正则表达式:

      // create a <div>' to hold the HTML:
      var div = document.createElement('div');
      // set the innerHTML of the <div> to the string of HTML:
      div.innerHTML = '<div class="class1 class2"><p id="id1">some <span class="class3">text about class="class4"</span></p></div>';
      // get all elements within the <div> that have a class attribute:
      classed = div.querySelectorAll('[class]'),
      // create an empty array to hold the found class-names:
        classes = [];
      
      // iterate over the elements with a class-attribute, using forEach:
      [].forEach.call(classed, function(el) {
        // iterate over the classes that the current element has, using 'classList':
        [].forEach.call(el.classList, function(c) {
          // if the current class (from the classList) isn't already in the array,
          // we add it to the array:
          if (classes.indexOf(c) === -1) {
            classes.push(c);
          }
        });
      });
      
      console.log(classes);

      参考资料:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-13
        • 2012-10-06
        • 1970-01-01
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多