CSharpBeginner CSharpBeginner - 3 months ago 10
HTML Question

Td inner elements

I'm very new at jQuery/Javascript.

I'm trying to know if to

td
element has more than one
li
element with text..

I have the follow
td
if has more than one
li
element with text.
Code sample:


<td class="tdClass"/>
<div id="div1Id" class="div1Class">
<ul class="ulClass">
<li id="" class="rtLI rtFirst">
<div class="rtMid">
<div>Text1</div>
</div>
</li>
<li id="" class="rtLI rtLast">
<div class="rtMid">
<div>Text2</div>
</div>
</li>
</ul>

</div>
</td>


And the follow if i have only one
li
element without text:


<td class="tdClass"/>
<div id="div1Id" class="div1Class">
<ul class="ulClas">
<li id="" class="rtLI rtFirst rtLast">
<div class="rtMid">&nbsp;</div>
</li>
</ul>

</div>
</td>


How i can know at the simple way (jQuery/javascript) if to my td has "inner elements"?
I see thats if has element the first
li
item have only
rtLI rtFirst
class and if not
rtLI rtFirst reLast
but how can i know that from my code?
Thanks

Answer

I'm basing this answer on your comment

i want to know if i have only one 'li' with inner div element with empty text.

As the wording of your actual question is less clear.


There appears to be a number of ways to achieve what you're after, they all begin with having a reference to your div element. In jQuery, you select an element by Id using a # selector

var $div = $('#divId');

(Note, as a common convention you can prefix variables which relate to a jQuery object with $ to distinguish them from other variables. Not essential, but a useful convention)

From there, your element with only blank text seems to have both classes rtFirst and rtLast. So you can count the number of children with both of these classes. If that count is equal to 1, then you have that element.

if($divId.find('.rtFirst.rtLast').length === 1){
    // you only have the one element with both rtFirst _and_ rtLast
}

Another way would be to count the number of children of the ul within your div

var numberofLis = $divId.children('ul').children().length;
if(numberofLis === 1){
    // you only have the one element
}

And there are countless other ways to achieve the same.

Comments