0

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);
    });
});
0

6 Answers 6

5
$('#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(', '));
});
Sign up to request clarification or add additional context in comments.

2 Comments

For some reason, this does not work, it doesn't print any ID's or classes to console when I paste HTML code into the textarea: jsfiddle.net/Yazpj/1525
Fixed a bunch of capitalization errors. Also, concat doesn't modify the array like push does, so need to assign the result (I could also use splice).
0

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.

9 Comments

OP doesn't want to remove class and id, they want to store in array.
.children only gets immediate children, not all descendants.
err I'm not looking to remove anything, just looking to put all classes and ID's in a block of HTML into an array. Thanks though.
$(codeInput) won't work if codeInput doesn't start with an HTML tag. And even if it does, find('*') will ignore the outermost tag, since it only searches descendants. See my answer for the way around these problems.
@eveo is this what you were looking for then?
|
0

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);
});

3 Comments

Missing id= in the first regexp?
You're only getting the first ID and class, not all of them.
@Barmar - I'm learning regex, and would appreciate you looking at my forked question off this answer when you get a chance: stackoverflow.com/questions/23326494/…
0
$(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);
    });
});

1 Comment

This only gives me the classes and ID's used on the current webpage housing the source code, not the text I paste into the textarea.
0
<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/

2 Comments

I think you've misunderstood what's supposed to be in the textarea. It's not a list of selectors, it's HTML code.
Read the first line of the question: a textarea where I paste a block of HTML code
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.