Jump to content

Best way to check an element's content?


Joshua4550

Recommended Posts

Okay, so I basically just want to check through an element, and count how many (for example) divisions it has.

 

I was thinking, the best way to do this would be a while/for statement?

 

Or is there a method for counting something in a string/value?

 

For EG:

<div id="meme">
  <div id="element1"> </div>
  <div id="element2"></div>
</div>

How would I go about (the best way) counting how many divisions there are with the name "element" + a number?

 

I'm thinking having a counter starting at one, and ask if the element id equals element + counter ?

 

Please help ;)

Link to comment
https://forums.phpfreaks.com/topic/202520-best-way-to-check-an-elements-content/
Share on other sites

If you just want to count the number of divs with the ID 'elementn', then you can do this:

 

function getDivCount()
{
    var divCount = 0;
    while(document.getElementById('element'+(divCount+1)))
    {
        divCount++;
    }

    return divCount;
}

 

Or are you wanting to count the divs specifically in the parent div 'meme'?

  Quote

Yeah, specifically in meme would be what I was wanting..

 

So you are saying there are other elements on the page with ids in the format 'elementn[/n]'? I wouldn't think so. But, OK, let's say you only want to find DIV objects within the DIV 'meme' which have ids in that format. This will do that for you:

 

<html>
<head>
<script type="text/javascript">

function getDivCount(parentID, childPrefix)
{
    var parentObj  = document.getElementById(parentID);
    var childCount = parentObj.childNodes.length;
    var divCount = 0;
    var childNode;

    for(childIdx=0; childIdx < childCount; childIdx++)
    {
        childNode = parentObj.childNodes[childIdx];
        if(childNode.tagName=='DIV' && childNode.id.substr(0, childPrefix.length)==childPrefix)
        {
            divCount++;
        }
    }
    return divCount;
}

</script>
</head>
<body>

Meme Div:
<div id="meme" style="border:1px solid black; width:300px;">
  <div id="element1">Meme Element 1</div>
  <div id="element2">Meme Element 2</div>
  <div id="element3">Meme Element 3</div>
  <div id="element4">Meme Element 4</div>
  <div id="element5">Meme Element 5</div>
  <div id="NONelement6">Meme NON Element 6</div>
</div>

<br />Not Meme Div:
<div id="NOTmeme" style="border:1px solid black; width:300px;">
  <div id="element7">Non Meme Element 1</div>
  <div id="element8">Non Meme Element 1</div>
  <div id="element9">Non Meme Element 1</div>
</div>
<br />
<button onclick="alert(getDivCount('meme', 'element'));">Count 'element' Divs in 'meme' Div</button>

</body>
</html>


Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.