eveo
eveo

Reputation: 2843

Extracting all CSS classes and ID's in a given HTML block

I have a textarea where I paste a block of HTML code. When I hit submit, I want to extract all CSS classes and ID's from that block and throw them into an array.

So far I have the submit working as well as the regular expression, but i don't know how to filter through the whole block and extract all instances where text matches my regular expression.

index.html

<body>
    <textarea id="codeInput"></textarea>
    <button id="submitCode">submit</button>
    <script src="functions.js"></script>
</body>

function.js

$(function() {
    $('#submitCode').click(function() {
        var codeInput = $('textarea#codeInput').val();
        console.log(codeInput);
    });
});

Upvotes: 0

Views: 729

Answers (6)

pixelFast
pixelFast

Reputation: 9

I had this very same challenge and modified the code by @Ryan to extract all (unique) classes and IDs, including when multiple classes are applied to the same element. It's very useful and works for any URL.

See http://jsfiddle.net/pixelfast/4uftwbm0/57/

Thank you.

<!-- HTML -->
<textarea id="codeInput" cols=50 rows=10></textarea>
<button id="submitCode">submit</button>

<!-- jQuery -->

var remoteURL = "https://getbootstrap.com";

function url_content(url) {
  return $.get(url);
}

url_content(remoteURL).success(function(data) {
  $('#codeInput').val(data);
});

$(function() {
  $('#submitCode').click(function() {
    var CSS_CLASSES = [];
    var CSS_IDS = [];
    var el = document.createElement('div');
    var text = $("#codeInput").val();
    el.innerHTML = text;
    var nodes = el.getElementsByTagName('*');
    for (var i = 0; i < nodes.length; i++) {
      var node = nodes[i];
      if (node.id.length > 0) {
        CSS_IDS.push(node.id);
      }
      if (node.className.length > 0) {
        var x = node.className.split(" ")
        $.each(x, function(index, val) {
          if (val != '') {
            CSS_CLASSES.push(val);
          }
        });
      }
    }
    console.log("CLASSES FOUND: ", unique(CSS_CLASSES));
    console.log("IDs FOUND: ", unique(CSS_IDS));
  });
});


function unique(list) {
  var result = [];
  $.each(list, function(i, e) {
    if ($.inArray(e, result) == -1) result.push(e);
  });
  return result;
}

Upvotes: 0

Barmar
Barmar

Reputation: 782489

$('#submitCode').click(function() {
    var codeInput = $('textarea#codeInput').val();
    var codeHTML = $('<div>', { html: codeInput }); // Parse the input as HTML
    var allIds = [];
    var allClasses = [];
    codeHTML.find('[id]').each(function() {
        allIds.push(this.id);
    });
    codeHTML.find('[class]').each(function() {
        allClasses = allClasses.concat(this.className.split(' '));
    });
    console.log("IDs: " + allIds.join(', '));
    console.log("Classes: " + allClasses.join(', '));
});

Upvotes: 5

Ryan
Ryan

Reputation: 14659

<textarea id="codeInput">
    <div id="hello"><div class="w"></div></div>
    <div id="world"></div>
    <div class="my-class"></div>
</textarea>
<button id="submitCode">submit</button>

$(function() {
    $('#submitCode').click(function() {
        var CSS_CLASSES = [];
        var CSS_IDS = [];
        var el = document.createElement( 'div' );
        var text = $("#codeInput").val();
        el.innerHTML = text;       
        var nodes = el.getElementsByTagName('*');
        for(var i = 0; i < nodes.length; i++) {
           var node = nodes[i];
            if(node.id.length > 0) {
              CSS_IDS.push(node.id); 
            }
            if(node.className.length > 0) {
              CSS_CLASSES.push(node.className);    
            }
        }
        console.log(CSS_CLASSES);
        console.log(CSS_IDS);
    });
});

http://jsfiddle.net/zeZ93/6/

Upvotes: 0

aromka
aromka

Reputation: 26

$(function() {
    $('#submitCode').click(function() {
        var ids = [], classes = [];        
        $("[id],[class]").each(function(i, el) {
            var id, c;
            if (id = $(this).attr('id')) {
                ids.push(id);
            }            
            if (c = $(el).attr('class')) {
                classes.push(c);
            }
        });
        console.log(ids, classes);
    });
});

Upvotes: 0

themerlinproject
themerlinproject

Reputation: 3582

Personally I like Barmar's solution the best, but this works (jsfiddle):

$('#submitCode').click(function() {
   var codeInput = $('#codeInput').val();
   var ids = codeInput.match(/id="(.*?)"/);
   var classes = codeInput.match(/class="(.*?)"/);
   var output = classes[1].split(" ");
   output.push( ids[1] );
   console.log(output);
});

Upvotes: 0

Joeytje50
Joeytje50

Reputation: 19122

Make your function.js something like this:

$(function() {
    $('#submitCode').click(function() {
        var codeInput = $('textarea#codeInput').val();
        var $input = $(codeInput);
        var attrs: {
            'class': [],
            'id': []
        };
        $input.find('*').each(function() {
            attrs.class.push($(this).attr('class'));
            attrs.id.push($(this).attr('id'));
        });
        attrs.class.push($input.attr('class'));
        attrs.id.push($input.attr('id'));
    });
});

That goes through each element in the input code, and removes their class and id attributes, by first going through all the children of the container element in the input, and then afterwards doing the same for the container element in the input.

Upvotes: 0

Related Questions