I am getting problem to get the text of parent span. This is code where I am implementing
<span> hello this is test <span>click here</span></span>
I want to get hello this test
content on click of click here
.
Thanks
I am getting problem to get the text of parent span. This is code where I am implementing
<span> hello this is test <span>click here</span></span>
I want to get hello this test
content on click of click here
.
Thanks
If you have no problem with jQuery, there is a basic solution like this
HTML
<span> hello this is test <span class="button">click here</span></span>
jQuery
$(document).ready(function(){
$('.button').on('click', function(){
var parentElement = $(this).parent().clone();
parentElement.children('span').remove()
alert(parentElement.text());
});
});
Change your HTML to:
<span> hello this is test <span onclick="showParentText(this)">click here</span></span>
and add the following function in the script tag:
window.showParentText = function(obj) {
var thisText = obj.outerHTML,
parentText = obj.parentNode.innerHTML;
alert(parentText.replace(thisText, ""));
}
Check fiddle here: http://jsfiddle.net/F7YFB/
First things first: you should always consult Html and Javascript documentation on mozilla site. Look at the code below. The html structured in such a way that after Element node always comes TextNode. Read more about this in docs. So, this text node you want to show after a child span element is clicked, thus you use DOM API to get what you want:
<script>
function respond_to_click_event(event) {
alert(event.target.previousSibling.wholeText);
}
</script>
<span> hello this is test
<span onclick="respond_to_click_event(event)">click here</span>
</span>
Maybe something like this if you are using jQuery,
$('span>span').parent('span').clone().find("span").empty().parent().text();
also a rough pure js solution
var childContent = document.querySelectorAll("span>span")[0].textContent;
var parentContent = "";
var allSpans = document.querySelectorAll("span");
allSpans = Array.prototype.slice.call(allSpans);
allSpans.forEach(function (spanEl) {
if (spanEl.textContent.replace(childContent,"").length>0) {
parentContent = spanEl.textContent.replace(childContent,"");
}
alert(parentContent);
});
However it is preferable if you add some kind of event as others have noted or class names, since this will get worse if you have more span children or parents etc
With jQuery, you may use this: $(this).parent().text();
.
For pure javascript, check this out: Get parent element of a selected text