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

如何用jQuery获取DOM元素的icon类名?解决匹配返回异常

Solution for Extracting Icon Class Names with jQuery

Hey there! I see the issue with your current code—let's break it down and fix it step by step.

What's Wrong with Your Current Code?

Your regex /icon-*/ isn't doing what you think it does. The * quantifier matches zero or more occurrences of the previous character (which here is the -), so it will only match icon or icon- (with any number of hyphens), not the full icon class name like icon-home. Additionally, the match() method returns an array of matches (or null if none are found), not a direct string—so you need to access the actual match value from that array.

Fix 1: Correct the Regular Expression

Use a regex that matches the full icon class name (from icon- up to the next whitespace or end of the string), then grab the first match from the result array:

jQuery('.nav_header').each(function() {
  // Match "icon-" followed by any non-whitespace characters
  var iconMatch = jQuery(this).attr('class').match(/icon-[^\s]+/);
  // Check if a match exists before accessing it to avoid errors
  if (iconMatch) {
    var icon_class = iconMatch[0];
    console.log(icon_class); // Will log "icon-home", "icon-address", etc.
  }
});

Fix 2: Split and Filter Class Names (More Readable)

If regex feels tricky, you can split the class attribute into an array and filter for the class that starts with icon-:

jQuery('.nav_header').each(function() {
  var classList = jQuery(this).attr('class').split(' ');
  // Find the first class that starts with "icon-"
  var icon_class = classList.find(className => className.startsWith('icon-'));
  console.log(icon_class);
});

For older browsers that don't support Array.find(), you can use Array.filter() instead:

var icon_class = classList.filter(className => className.startsWith('icon-'))[0];

Why This Works

Both methods target the specific class starting with icon- and extract it as a string, which is exactly what you're looking for. The first method uses regex to directly match the pattern, while the second breaks down the class list into manageable parts for easier filtering.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:35:54