gbs
gbs

Reputation: 7276

Grab some text from a markup string using jQuery

I have the following markup:

<span>
Some text blalablalalbal<br/><br/>
"You are Awesome" <br/><br/>
----What can I do for you?<br/><br/>
</span>

Now I want to hide first line and modify the last line.

How can I grab those text using jQuery?

Note:

1: There are multiple instances of similar code-block but with different text. So I won't be able to hardcode. I am wondering if I can split it using
tags somehow?

2: If it can be done in server-side code in C#, that is fine as well.

Upvotes: 2

Views: 169

Answers (4)

Mark Vincze
Mark Vincze

Reputation: 8043

Or you can put the three lines in three different spans with ids. Something like:

<span>
<span id="sentence1">Some text blalablalalbal</span><br/><br/>
<span id="sentence2">"You are Awesome" </span><br/><br/>
<span id="sentence3">----What can I do for you?</span><br/><br/>
</span>

And hiding the first sentence with jquery:

$("span#sentence1").hide();

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

You can split the line breaks and modify the array:

var elm = $('span'),
    lines = elm.html().split('<br>');

lines.shift(); // removes the first
lines[lines.length-3] += '-modified'; // modify the last

elm.html(lines.join('<br>'));

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101614

You can play around with textnodes doing something like this.


Update

var $nodes = $('span').contents().map(function(a,b){
    return (b.nodeType===3?b:null);
});

// hide first line
$($nodes.get(0)).wrap('<span style="display:none;" />');
$nodes.get(2).data = "foo";

Working example of what I mean.

Upvotes: 3

Alfred Fazio
Alfred Fazio

Reputation: 956

CSS has :first-line and :last-line modifiers.

Try:

span:first-line {
  display: none;
}

Use jQuery with selector to modify last line:

var content = $('span:last-line').html();
content += " - Modified";
$('span:last-line').html(content);

Upvotes: 0

Related Questions