user1355300
user1355300

Reputation: 4987

get parent divtext with jQuery

In the following markup, I want to select the text inside the .title but exclude the text which is inside the .button.

<span class="title">
    Title Text
    <span class="button">Button</span>
</span>

I am trying following code but it selects the .button text also. How can I exclude that without changing the HTML.

$('.title').on('click', '.button', function() {
    var item = $(this).parent();
    var title = item.text();
    alert(title);
});

Upvotes: 2

Views: 60

Answers (5)

Manoj
Manoj

Reputation: 5071

Try this,

$('.title').on('click', '.button', function() {
  var $item = $(this).parent();
    var title = $item.contents().get(0).nodeValue;
    alert(title);
});

Working Demo

Upvotes: 4

techfoobar
techfoobar

Reputation: 66693

Yet another way, using the built-in previousSibling property (which includes text nodes as well) [just for information sharing].

$('.title').on('click', '.button', function() {
    alert(this.previousSibling.nodeValue);
    // trim the above as it can contain newlines, spaces, etc. as in the source
});

Upvotes: 3

LcSalazar
LcSalazar

Reputation: 16841

You can clone the element, and remove the children. Then get the text of the cloned element.

$('.title').on('click', '.button', function() {
    var title = $(this).parent().clone().children().remove().end().text();
    alert(title);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="title">
    Title Text
    <span class="button">Button</span>
</span>

Upvotes: 2

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

you can replace the text retrived from the button with '' in the parents text http://jsfiddle.net/94u3rf6b/

$('.title').on('click', '.button', function() {
    var item = $(this).parent();
    var title = item.text().replace($(this).text(),'');
    alert(title);
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337627

You need to retrieve value of the textNode. Try this:

$('.title').on('click', '.button', function() {
    var $item = $(this).parent();
    var title = $item.contents().get(0).nodeValue;
    alert(title);
});

Working fiddle

Upvotes: 4

Related Questions