简体   繁体   中英

Find the parent of a precise child to then select a child with jQuery

I have this simple example here:

<div class = "container">
   <div id = "jwplayer-0_wrapper"></div>
   <script type="text/javascript"></script>
</div>

And so What my code is supposed to do is so look wether or not there's a div with the id of "jwplayer-0_wrapper"

 if ($('#'+divId).length == 1 ) {

Then I need to select its direct parent, to get to its child>script and make it a .text() to be able to use the script content inside a variable. So I'm stuck on the selector problem of getting the script content. Maybe there's another way of getting the script with out even using its parent? They will always be inside the same parent div.

针对您的特定问题尝试以下操作:

$('#' + divId).next().text() ;

This should work to grab the script tag's inner text.

if ($('#'+divId).length == 1 ) {
    var scriptNode = $('#'+divId).parent().find('script').text();
}

I got my first answer wrong. Select the div, then navigate to the parent and select the text of the 'script' child.

$('#' + divId)
    .parent()
    .children('script')
    .text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM