You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用jQuery获取JSON中所有标签类名及嵌套元素class属性

Hey there, let's walk through how to solve this problem using jQuery. Here's a step-by-step breakdown with code examples tailored to your JSON data:

步骤1:解析JSON并准备可操作的HTML结构

First, we need to pull the escaped HTML string from your JSON, then load it into a temporary DOM container so jQuery can interact with it. The .html() method will automatically handle the escaped characters like < and >.

// Your sample JSON data (I filled in the truncated end for testing)
const jsonData = [
  {
    "Field1": "<header class=\"main-header dark-bg\">\n\t<div class=\"row\">\n\t\t<div class=\"col-xl-3\">\n<a class=\"icons-darkbg-slogan main-header__slogan\" data-event_engagement=\"\" data-event_linktype=\"internal page link\" data-event_source=\"DAM|active|de|de|/\" data-event_target=\"/\" data-event_title=\"Header Home::Slogan\" href=\"/\" target=\"_self\">Slogan</a>\n\t\t</div>\n\t</div>\n</header>"
  }
];

// Extract the HTML string from JSON
const rawHtml = jsonData[0].Field1;
// Create a hidden temporary container to hold the HTML
const $tempDom = $('<div>').html(rawHtml);
步骤2:获取所有标签的类名(去重)

We'll traverse every element in the temporary DOM, collect all class names, and use a Set to avoid duplicates (since multiple elements might share the same class).

const allUniqueClasses = new Set();

// Loop through every tag in the HTML
$tempDom.find('*').each(function() {
  const elementClasses = $(this).attr('class');
  if (elementClasses) {
    // Split multi-class strings (e.g., "main-header dark-bg" becomes two separate classes)
    elementClasses.split(' ').forEach(className => allUniqueClasses.add(className));
  }
});

// Convert Set to array for easier reading/logging
console.log('All unique class names across all tags:', Array.from(allUniqueClasses));
步骤3:提取所有div(含内部嵌套div)的class属性

To target only divs (including nested ones), we use find('div') and collect each div's class details, including its position if needed.

const divClassDetails = [];

// Loop through every div (including nested ones)
$tempDom.find('div').each(function(divIndex) {
  const divClasses = $(this).attr('class');
  divClassDetails.push({
    divNumber: divIndex + 1,
    classes: divClasses ? divClasses.split(' ') : []
  });
});

console.log('Class attributes for all divs (including nested):', divClassDetails);

输出结果说明

  • For all tags, you'll get a list like: ["main-header", "dark-bg", "row", "col-xl-3", "icons-darkbg-slogan", "main-header__slogan"]
  • For divs, you'll get an array of objects showing each div's classes:
    [
      { divNumber: 1, classes: ["row"] },
      { divNumber: 2, classes: ["col-xl-3"] }
    ]
    

内容的提问来源于stack exchange,提问作者Zabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:03:44