Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get .text() but not the text in span

This is my jQuery part that makes my menu for my pages.

function fetchmenus() {
    $.getJSON('sys/classes/fetch.php?proccess=1', function(status) {
        // get line status
        $.each(status, function(i, item) {
            if (item.id == "1") {
                active = "class='active'";
                lastpageid = item.href;
            }
            else {
                active = "class='nonactive'";
            }
            $('<li id="' + item.href + '" ' + active + '><a href="#' + item.href + '">' + item.menuTitle + '<span class="menuspan" id="' + item.href + '"></span></a></li>').appendTo('#menuarea ul#mainmenu');

        });
    });
}

What I want to do is get the item.menuTitle in the <a but before the <span>.

Currently I do it on this way:

$('ul#mainmenu li').live('click', function(event) {
    //alert(this.id);
    $("li#" + lastpageid).removeClass();
    fetchpage(this.id);

    $("#largemenutop").html($(this).text());

    $("li#" + this.id).addClass("active");
    lastpageid = this.id;
});;

Is there a better way to do this?

like image 257
RussellHarrower Avatar asked May 06 '11 14:05

RussellHarrower


2 Answers

Nice solution Herman, though it can be reduced to something like this:

JS

$('li a').contents().filter(function() {
    return this.nodeType == 3;
}).text();

HTML

<li><a href="#">Apple<span>hi</span> Juice</a></li>

Will return Apple Juice

Fiddle: http://jsfiddle.net/49sHa/1/

like image 188
Gary Green Avatar answered Oct 07 '22 10:10

Gary Green


Yes, you can select only the text contents of the element, like this:

 var text = '';
 $('a').contents().each(function(){
    if(this.nodeType === 3){
     text += this.wholeText;
    }
 });
 $("#largemenutop").html(text);
like image 40
Herman Schaaf Avatar answered Oct 07 '22 09:10

Herman Schaaf