Search code examples
javascriptjqueryif-statementprepend

find out the parent of a link and pre-pend it with something


I'm trying do something like this

if ($(this).parent() == $('div.propdata')){

    $(this).prepend('<a class="booknow2 sidelink" href="../../availability/default.aspx"><span>Book now &raquo;</span></a>');

}

By the way $(this) is evenprop.

Can't seem to get it to work.

This is my code

<div class="propdata" id="FARM"><div class="evenprop">This is where the prepend would be</div></div>

I need it to only prepend that bit if the parent of evenprop is propdata.


Solution

  • You can use a selector on .parent() and .length to see if it matched, like this:

    if ($(this).parent('div.propdata').length){
      $(this).prepend('<a class="booknow2 sidelink" href="../../availability/default.aspx"><span>Book now &raquo;</span></a>');
    }
    

    You can give it a try here, since .parent() only returns the immediate parent if it matches the selector, it's a quicker test than .parent().is(selector).