Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the first span element which is not empty

From a group of span elements, I want to get the values of the first occurrence of a span that is not empty.

I have this HTML

<span class="map_multi_latitude"></span>
<span class="map_multi_longitude"></span>
<span class="map_multi_latitude">30.201998</span>
<span class="map_multi_longitude">120.990876</span>

I have this Jquery before but I want to make it work such that "the first span whose text is not empty":

initialLat = $('span.map_multi_latitude:first').text();
initialLng = $('span.map_multi_longitude:first').text();

thanks in advance!

like image 602
yretuta Avatar asked Jun 15 '11 03:06

yretuta


People also ask

How do I check if a span is empty?

Use the childNodes property to check if a span element is empty. The childNodes property returns a NodeList of the element's child nodes, including elements, text nodes and comments. If the property returns a value of 0 , then the span is empty.

What is a span element?

The <span> HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang .

What is the span tag?

The <span> tag is an inline container used to mark up a part of a text, or a part of a document. The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute.

What is the use of div and SPAN tag in HTML?

Span and div are both generic HTML elements that group together related parts of a web page. However, they serve different functions. A div element is used for block-level organization and styling of page elements, whereas a span element is used for inline organization and styling.


2 Answers

This will work:

$('span:not(:empty):first').text()

or these:

$('span:not(:empty):eq(0)').text()
$('span:not(:empty)').eq(0).text()
$('span:not(:empty)').slice(0,1).text()
$('span:not(:empty)').first().text()
like image 165
user113716 Avatar answered Nov 15 '22 14:11

user113716


initialLat = $('span.map_multi_latitude:not(:empty):first').text();
initialLng = $('span.map_multi_longitude:not(:empty):first').text();
like image 37
amit_g Avatar answered Nov 15 '22 15:11

amit_g