How to get the text of parent element using jquery?

28,631

Solution 1

The problem with doing:

$(this).parent().text();

is that it will get ALL the text within the div (sometext AND delete).

I'm assuming you only want the text in the div and not the link.

I've knocked up an example on jsFiddle:

http://jsfiddle.net/HK794/

Ideally you might want to wrap the text in a span, like:

<div id="div1"><span>sometext</span><a href="#">delete</a></div>

Then your JavaScript would be:

$("a").click(function(e){

    $div = $(this).parent("div");

    id = $div.attr("id");

    text = $div.find("span").text();

    alert( text  );

    e.preventDefault();
});

EDIT

As @DarthJDG states if you don't want to change your markup, any these would also work:

text = $div.get(0).childNodes[0].nodeValue;

//OR    
text = $div[0].childNodes[0].nodeValue;

//OR
text = $div.get(0).firstChild.nodeValue;

//OR
text = $div[0].firstChild.nodeValue;

//OR

//Gets the first text node
$div.contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE;
}).text();

Solution 2

        var content;
        $(this).parent().contents().filter(function() {
            return this.nodeType == 3;
        }).each(
                function(i,el){
                    content = content + $(el).text();
                }
        );

This sets content to the value of any direct children which are text.

Share:
28,631
Maverick
Author by

Maverick

Updated on August 01, 2020

Comments

  • Maverick
    Maverick almost 4 years

    I have a div which contains a delete hyperlink, onlick of it, I want the text of the div tag. How is it possible in jquery?!

    <div>sometext<a href="#">delete</a></div>
    

    I want to get the text of div tag 'sometext' and if possible the id of that div too. Any ideas?!

    • Chad
      Chad almost 13 years
      Are you wanting to just get sometext because the normal .text() method everyone is suggesting will NOT get just sometext it will actually return sometext delete becasue the <a/> is within the <div/>
    • Maverick
      Maverick almost 13 years
      yes, I want to just get the sometext!
    • Kike Gamboa
      Kike Gamboa about 7 years
  • RJD22
    RJD22 almost 13 years
    it should strip all html now.
  • Maverick
    Maverick almost 13 years
    I am afraid it still giving the same value!
  • DarthJDG
    DarthJDG almost 13 years
    Just in case you wouldn't want to change your HTML markup, you could extract the first text node from the HTML DOM: $(this).parent()[0].firstChild.nodeValue
  • Tomgrohl
    Tomgrohl almost 13 years
    @tfbox Yes your right but it would be easier to change the HTML markup than write some JavaScript which just seems hacky.
  • Tomgrohl
    Tomgrohl almost 13 years
    Good point @DarthJDG, added it into answer. Forgot about using that.
  • Matt
    Matt almost 13 years
    @ nickf yep thats why I added the text above my answer :) was jsut giving him all options