atif
atif

Reputation: 1693

How to get number of html elements in a string?

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

Answers (6)

THEtheChad
THEtheChad

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

Offbeatmammal
Offbeatmammal

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

ameya rote
ameya rote

Reputation: 1114

  1. Get all elements in the document (document.getElementsByTagName('*'))
  2. Do a regular expression match on the element's className attribute for each element

You can use jQuery: $("html *") which will return all elements between the html tags

  1. for names you must use $("html *").attr('name')
  2. for values $("html *").val() or $("html *").attr('value')

Upvotes: 1

Sahal
Sahal

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

Ram
Ram

Reputation: 144699

var s = "<div> some text<div><label>some text</label></div></div>";   
var length = $(s).find('*').andSelf().length;

http://jsfiddle.net/jCW7Z/

Upvotes: 4

IanO.S.
IanO.S.

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

Related Questions