maddogandnoriko
maddogandnoriko

Reputation: 1002

Get parent element text without children's text

I seem to be digging a deeper and deeper hole for myself, but I am determined to solve this now.

I am getting elements and testing to see if they have children, with the help of some very smart people here I have gotten that far. Now I need to get the parents text minus the childrens text. So below when I get information element, the text is information credits lorem ipsum, I just need Information.

<ul id="navMenu">
  <li id="home"><a href="#home" rel="ajax">Home</a></li>
  <li id="information"><a href="#information" rel="ajax">Information</a>
    <ul>
      <li><a href="#credits" rel="ajax">Credits</a></li>
      <li><a href="#lorem_ipsum" rel="ajax">Lorem Ipsum</a></li>
    </ul>
  </li>
  <li id="faqs"><a href="#faqs" rel="ajax">FAQs</a></li>
  <li id="contact"><a href="#contact" rel="ajax">Contact</a></li>
</ul>

And here is the jquery/javascript:

$('#test').load('../common.html #navMenu', function() 
{
  $.each($("#test #navMenu li"), function(i,v) 
  {
    if ($(v).find('li').length) 
    {
      var x = $(v).clone().children().remove().end().text();
      alert('This Element('+x+') has children');
    }
  });
});

The above script is returning empty spaces for the information element.

Upvotes: 0

Views: 900

Answers (2)

Tessmore
Tessmore

Reputation: 1039

This would give information only the text 'Information'.

$('#test').load('../common.html #navMenu', function() 
{
  $.each($("#test #navMenu li"), function(i,v) 
  {
    var information = $(this).find('a').first().text();

    if ($(v).find('li').length) 
    {
      var x = $(v).clone().children().remove().end().text();
      alert('This Element('+x+') has children');
    }
  });
});

I guess you could use $(v) instead of $(this) but for readability I prefer using $(this)

Upvotes: 1

Alex Peattie
Alex Peattie

Reputation: 27647

Do you not just want the text of the <a> element?:

if ($(v).find('li').length) {
  $(v).find('> a').text();
}

Upvotes: 3

Related Questions