views:

24

answers:

1

Hi

Using jQuery I would like to locate a preceding node from a given node. The preceding node and the given node may not have the same parent node! Please check the following fragment:

<div class="container">
<div id="sec1">
    <p>Some text</p>
    <p><b>Some</b> text<</p>
    <p>Some <b>more</b> text</p>
</div>
<div id="sec2">
    <p>just a text</p>
</div>
<div id="sec3">
    <p>another <span id="cursorPos1"></span>text</p>
    <p><b>yet</b> another<span id="cursorPos2"></span> text</p>
</div>

Supposing if the current given node is $("span#cursorPos1"), and what I would like to locate is the preceding bold text, then the result should be "<b>more</b>". Here, the given node is in div#sec3, and the target preceding node is in div#sec1.

If the current given node is $("span#cursorPos2"), then the preceding bold text is "<b>yet</b>". Here, both the given node and the target preceding node are in the same div#sec3.

Basically, the hierarchy should not be considered at all. From a given node the selector should simply find the preceding match.

Please let me know on how this can be done.

Thanks
Srikanth

+1  A: 

Not a very nice solution, but i think this does the trick. Idea is to find all bold tags and the cursor element, look for position of the cursor in the resulting array, and then return the element before it.

just threw this together, there are probably better ways. if you use this, some error checking is probably in order too.

prevBold = function(myId) {

var boldAndMe = $('#' + myId + ', b').toArray();
    var me = $('#' + myId).get(0);
    var myPos = boldAndMe.indexOf( me );

    return myPos > 0 ? $( boldAndMe[myPos-1] ) : null;

}
second
Thank you so much. It works fine, and for now I will settle with this solution.
Srikanth Vittal