Randomblue
Randomblue

Reputation: 116283

text between anchor elements in a paragraph

I have a paragraph with text and anchors.

Given an anchor $myAnchor within the paragraph, I can get the immediately following one:

$nextAnchor = $myAnchor.next('a');

How do I get the text/HTML between these two anchors?

Upvotes: 3

Views: 327

Answers (3)

svrx
svrx

Reputation: 634

To get the text between 2 anchors o can do something like this.

var a1 = $('#anchor1');
var a2 = $('#anchor2');

var contents = a1.parent().contents();

var s, e;
for(var i = 0; i<contents.length; i++){
    if($(contents[i]).is(a1)){
        s = i 
    }
    if($(contents[i]).is(a2)){
        e = i
    }
}

var text = contents.slice(s + 1,e).text().trim();

If you know that there is only one element in betewwen u can use the nextSibling method described.

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185933

Here you go:

$myAnchor[0].nextSibling.nodeValue

Live demo: http://jsfiddle.net/3Xp6G/1/

So, nextSibling will give you a reference to the next sibling node (which is a Text node), and then nodeValue will return the text-content of that Text node.

Btw [0] is required after $myAnchor because nextSibling is a property of DOM nodes, not jQuery objects, and [0] returns the first DOM element from the jQuery object.

You can also use .trim() at the end to get rid of the useless white-space (if there is any).

Upvotes: 2

Paul
Paul

Reputation: 2206

Edit: misunderstood question.

See here: http://jsfiddle.net/RkEwR/

Use .contents()

Upvotes: 0

Related Questions