lidermin
lidermin

Reputation: 2832

Invert text selection from DIV

I have several div elements like this:

<div class="newsContainer">
    <div class="deleteBoxIcon">
        <img alt="Delete" src="close_mark.png">
    </div>
    <div class="newsImage">
        <img alt="NewsImage" src="umbrella.png">
    </div>
    <div class="newsContent">
        <b>Here goes a title</b><br>
        Here goes some content.
    </div>
</div>

Based on certain conditions, I retrieve one of those divs and save it into an object (draggable), now I need to extract the title and content texts to input controls.

Getting the title is not difficult for me, I'm just doing this:

var title = $('.newsContent > b', $(draggable)).text();

But the hard part for me is getting the content, I've tried this but it's not working because it retrieves all the text (including the title):

var content = $(':not(.newsContent > b)', $(draggable)).text();

Hope you can help me to get only the content part of a div like this.

Upvotes: 0

Views: 119

Answers (3)

RightSaidFred
RightSaidFred

Reputation: 11327

If you just want the last bit of text:

$('.newsContent', draggable).contents().last()[0].data;

  • .contents() method gives you all child nodes, including text nodes

  • .last() gives you the last node, which is the one you want

  • [0] extracts the text node from the jQuery object

  • .data gives you the text content of the node


Or you could replace [0].data with .text().

$('.newsContent', draggable).contents().last().text();

Upvotes: 0

wsanville
wsanville

Reputation: 37516

You should change your markup to make writing your JavaScript easier. Wrap your markup, excluding the heading within another tag, and then select it.

Example:

<div class="newsContent">
    <h2>Here goes a title</h2>
    <div class="newsDesc">
        <p>Here goes some content.</p>
    </div>
</div>

Then, use $('.newsContent .newsDesc', $(draggable)).text();

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

Try this:

var title = $('.newsContent > b').text();
var content = $.trim($('.newsContent').text().replace(title, ""));

Example fiddle

Upvotes: 1

Related Questions