Wednesday, July 9, 2014

JQuery–find parent with partial div id

Let’s say you need to find a parent of a DIV and you know part of the DIV id. For example, you want to turn the background color blue of the parent of the div id=toolbarnav, which has a div id that starts with WebPartWPQ (use ^ to do this).  There are multiple divs on the page that have different variations of this ID, but only one will be the parent of toolbarnav.

HTML

<div id="y">I'm in the Y div
           <div id="WebPartWPQ4"> I'm in WebPartWPQ4 div </div>
       </div >       
      <div id="x">I'm in the x div
       <div id="WebPartWPQ3">
           <a href="">I'm in the WebPartWPQ3 div - my child is toolbarnav</a>
           <div >
             <div id="toolbarnav">I'm in toolbarnav div</div>        
           </div>
       </div>
      
       <div id="DivID">
         I'm in DivID
       </div>

JQuery Code

$(document).ready(function() {
   
if (!
$('#toolbarnav').parents("div[id^='WebPartWPQ']").hasClass('turnblue')
    )
{
    $('#toolbarnav').parents("div[id^='WebPartWPQ']").addClass('turnblue');
}
    else { $('#toolbarnav').parents("div[id^='WebPartWPQ']").removeClass('turnblue');}
   
});

 

image

No comments:

Post a Comment