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?!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With