Search code examples
javascripthtmldomuserscripts

Using DOM nextSibling


I'm writing a userscript for a page which has this HTML code block..

<span id="mediaSetUfiLikeLink">
    <button class="like_link stat_elem as_link" title="Like this item" type="submit" name="like">
        <span class="default_message">Like</span>
        <span class="saving_message">Unlike</span>
    </button>
</span>

<span>
    <a href="/ajax/sharer/?s=3&appid=2305272732&p[]=1012781954&p[]=2063763" rel="dialog">Share</a>
</span>

I need to add an id tag to the last span block. (below one)

<span>
    <a href="/ajax/sharer/?s=3&appid=2305272732&p[]=1012781954&p[]=2063763" rel="dialog">Share</a>
</span>

I'm got to this point using this,

document.getElementById("mediaSetUfiLikeLink").getElementsByTagName("span")[1];

I tried getting the last span using nextSibling like this, which returned null

document.getElementById("mediaSetUfiLikeLink").getElementsByTagName("span")[1].nextSibling;

Can someone please help me out with this? Just to be clear once again, I want to 'gain access' to the last span block so that I can add an id attribute to it..

P.S - I need to do this without using jQuery or any other external library. Pure JavaScript only.

Thank you


Solution

  • document.getElementById("mediaSetUfiLikeLink").nextElementSibling;
    

    or

    function nextElementSibling( elem ) {
    
        do {
    
            elem = elem.nextSibling;
    
        } while( elem && elem.nodeType !== 1 );
    
        return elem;
    }
    
    var elem = nextElementSibling( document.getElementById("mediaSetUfiLikeLink") );
    

    http://jsfiddle.net/tXGQ6/