1

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

Elon Than
  • 9,603
  • 4
  • 27
  • 37
user2870078
  • 11
  • 1
  • 2

5 Answers5

1

If you have no problem with jQuery, there is a basic solution like this

http://jsfiddle.net/7gbNK/55/

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());
    });
});
Donovan Charpin
  • 3,567
  • 22
  • 30
1

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/

Vishal
  • 2,030
  • 22
  • 27
1

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> 
Stanislav
  • 66
  • 3
0

Maybe something like this if you are using jQuery,

$('span>span').parent('span').clone().find("span").empty().parent().text();

http://jsfiddle.net/fgUGa/1/

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);
});

http://jsfiddle.net/fgUGa/2/

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

melc
  • 11,523
  • 3
  • 36
  • 41
-1

With jQuery, you may use this: $(this).parent().text();.

For pure javascript, check this out: Get parent element of a selected text

Community
  • 1
  • 1
HasanAboShally
  • 18,459
  • 7
  • 30
  • 34