Reputation: 1693
How to get number of HTML elements (HTML tags) in a string?
For example I have this string:
<div> some text
<div>
<label>some text</label>
</div>
</div>
Now how would I find number of html tags in this string? The result in the case above will be 3.
I did tried this, thought it will work but it didn't:
$('*').length;
Upvotes: 1
Views: 3528
Reputation: 2432
If you're using jQuery (and it looks like you are), the easiest way would be to use code similar to the following:
var count = $( yourString ).find('*').andSelf().length
However, if you're using vanilla javascript, the implementation would look more like this:
var temp = document.createElement('div');
temp.innerHTML = yourString;
var count = temp.getElementsByTagName('*').length;
Upvotes: 3
Reputation: 8236
A small, self documenting, example :)
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>List Elements</title>
</head>
<body>
<div>some text
<div>
<label>some text</label>
</div>
</div>
<script>
var x=document.getElementsByTagName('*');
console.log(x.length)
for (i=0;i<x.length;i++) {
console.log(x[i]);
}
</script>
</body>
</html>
Upvotes: 0
Reputation: 1114
You can use jQuery: $("html *") which will return all elements between the html tags
Upvotes: 1
Reputation: 4146
You can do it like this,
Put the string in to some hidden div
like
$('#myHiddenDiv').html(string);
then
You can gen number of children under it
This will tell you number of html elements under the body
var count = $("#myHiddenDiv> *").length;
or:
var count = $("#myHiddenDiv").children().length;
Your div will be like this
<div id="myHiddenDiv" style="display:none"></div>
Upvotes: 0
Reputation: 144699
var s = "<div> some text<div><label>some text</label></div></div>";
var length = $(s).find('*').andSelf().length;
Upvotes: 4
Reputation: 1382
Possible way to do it: http://api.jquery.com/length/
check out Find number of element in string with jQuery
for example
$( '.myClass', myData ).length;
(although this might not show outermost tags)
Upvotes: 0