如何用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:
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);
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));
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

