jishan siddique
jishan siddique

Reputation: 1895

How to load all font-awesome icon in dropdown control

I want to add all font-awesome icon in dropdown is there any way to read all icon in font-awesome.css and bind it dropdown control.

Like eg. Using any regex example or any other way read all icon class and bind in select control.

Currently, I have to add static as below example is there any way to read dynamic all class.

$(document).ready(function() {
    var iconArray = new Array(
      "fa-arrow-circle-down",
      "fa-user",
      "fa-plus",
      "fa-minus"
    );
    for(var i=0;i<iconArray.length;i++)
    {
      $(".jsIcon").append("<option>"+iconArray[i]+"<option>");
    }
});
<!DOCTYPE html>
<html>
<head>
   <title>font-awesome</title>   
   <!-- FONT AWESOME ICONS -->
   <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<i class="fa fa-arrow-circle-down"></i> Font Awesome
</div>
<div>
<i class="fa fa-user"></i> Font Awesome User iCon
</div>
<div>
<i class="fa fa-plus"></i> Font Awesome User iCon
</div>
<div>
<i class="fa fa-minus"></i> Font Awesome User iCon
</div>
<div>
<select class="jsIcon">
</select>
</div>
</body>
</html>

Thanks in advance.

Upvotes: 0

Views: 1056

Answers (1)

Eldar
Eldar

Reputation: 10790

In theory, you can use the code snippet below. It is blocked by browser CORS policy because it has a CDN link. For local CSS file, it should work fine.

$(document).ready(function() {
  const sheet = document.styleSheets[0]; // font-awsome one
  let iconArray = Array.from(sheet.cssRules)
    .filter(r => r.type === CSSRule.STYLE_RULE &&
      r.selectorText.indexOf("fa-") > -1 &&
      r.selectorText.indexOf("::before") > -1)
    .map(r => {
      return {
        selector: r.selectorText.replace("::before", ""),
        style: r.style.content[1]
      }
    });
  for (let i = 0; i < iconArray.length; i++) {
    $("select").append(`<option value="${iconArray[i].selector}">${iconArray[i].style} ${iconArray[i].selector}`);
  }
});
select {
  font-family: 'Font Awesome', 'sans-serif';
}
<!DOCTYPE html>
<html>

<head>
  <title>font-awesome</title>
  <!-- FONT AWESOME ICONS -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

</head>

<body>
  <div>
    <i class="fa fa-arrow-circle-down"></i> Font Awesome
  </div>
  <div>
    <i class="fa fa-user"></i> Font Awesome User iCon
  </div>
  <div>
    <i class="fa fa-plus"></i> Font Awesome User iCon
  </div>
  <div>
    <i class="fa fa-minus"></i> Font Awesome User iCon
  </div>
  <div>
    <select class="jsIcon">
    </select>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>

</html>

Upvotes: 1

Related Questions