How to get parent text using jquery?

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

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

I want to get the text of the div tag "sometext" and, if possible, the identifier of this div. Any ideas ?!

+7
source share
6 answers

Problem with execution:

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

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

I assume that you only want text in a div, not a link.

I applied the jsFiddle example:

http://jsfiddle.net/HK794/

Ideally, you can wrap text in between, for example:

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

Then your JavaScript will look like this:

 $("a").click(function(e){ $div = $(this).parent("div"); id = $div.attr("id"); text = $div.find("span").text(); alert( text ); e.preventDefault(); }); 

EDIT

As pointed out by @DarthJDG, if you don't want to change your markup, any of these will 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(); 
+12
source
  var content; $(this).parent().contents().filter(function() { return this.nodeType == 3; }).each( function(i,el){ content = content + $(el).text(); } ); 

This sets the content to the meaning of any direct children that are textual.

+1
source
 $('a').click(function() { var id = $(this).parent('div').attr('id'); var html = $(this).parent('div').html().replace(/<.*>/g, ""); alert(html); }); 
0
source

Although adding a span tag will probably be more efficient

http://jsfiddle.net/tN8Mv/

 $("a").click(function(){ var text = $(this).parent().clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text(); alert(text); }); 
0
source
 mySiblingtext=""; myParentId = ""; $('a').click(function(){ var mypart = $(this)[0].previousSibling; mySiblingtext= $(mypart).text(); myParentId = $(this).parent().attr('id'); alert(mySiblingText+myParentId); }); 

jQuery skips text nodes for all of its crawl methods (except .contents ()). To access the previous sibling, then the text in this case, regardless of the type of nodeType, you can access the DOM node, and then use the .previousSibling property. Then you can access the text of this element.

Access to the identifier if the parent is also simple.

Example script page: http://jsfiddle.net/MarkSchultheiss/FuQ6g/

NOTE. One of the advantages of this method is that you have type markup:

 <div id='aparent'>sometext<a href="#">delete</a>stuff after</div> 

the text "material after" is not selected.

0
source

jQueryElement.parent () text () ;.

-one
source

All Articles