如何使用jquery获取父元素的文本?

我有一个包含删除超链接的div,点击它,我想要div标签的文本。 怎么可能在jquery?!

sometextdelete

我想得到div标签’sometext’的文本,如果可能的话也得到div的id。 有任何想法吗?!

做的问题:

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

是它将获得div中的所有文本(sometext AND delete)。

我假设你只想要div中的文本而不是链接。

我在jsFiddle上打了一个例子:

http://jsfiddle.net/HK794/

理想情况下,您可能希望将文本换行,例如:

 
sometextdelete

然后你的JavaScript将是:

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

编辑

正如@DarthJDG所述,如果您不想更改标记,那么任何这些也可以起作用:

 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(); 
  var content; $(this).parent().contents().filter(function() { return this.nodeType == 3; }).each( function(i,el){ content = content + $(el).text(); } ); 

这将内容设置为任何直接子项的值,即文本。

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

虽然添加span标签可能会更有效

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); }); 
 mySiblingtext=""; myParentId = ""; $('a').click(function(){ var mypart = $(this)[0].previousSibling; mySiblingtext= $(mypart).text(); myParentId = $(this).parent().attr('id'); alert(mySiblingText+myParentId); }); 

jQuery跳过文本节点的所有遍历方法(.contents()除外)。 要访问上一个兄弟,然后在这种情况下发送文本,无论nodeType如何,您都可以访问DOM节点,然后使用.previousSibling属性。 然后,您可以访问该元素的文本。

如果父母也很简单,则访问Id。

示例小提琴页面: http : //jsfiddle.net/MarkSchultheiss/FuQ6g/

注意:此方法的一个优点是,如果您有以下标记:

 
sometextdeletestuff after

未选中“之后的东西”文本。

jQueryElement.parent()文本();