当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - jquery complex selector by element and class starting with

问题描述:

I'm using jQuery in my website.

I want to select all the <hr> elements through jQuery when class starts with line-rooms-sphere. <hr> elements have more than one class.

This is my html:

<hr class="line-rooms-sphere-4 rooms-hidden"/>

// There are 5 hr like this one

This is my jquery code:

$('hr [class^="line-rooms-sphere"]') // => Not working, Why?

$('[class^="line-rooms-sphere"]') // => This Works well

I want to get all the <hr> elements when they have the wanted class (in this case, starting with line-rooms-sphere).

Any help? Thanks

网友答案:

Your first example:

$('hr [class^="line-rooms-sphere"]') // => Not working, Why?

Does not work as you have a space between the hr and the attribute selector. The jQuery selector engine follows CSS rules, so a space means that the second rule should be looked for within the first selected element.

Instead the attribute you want is on the hr itself, so no space is required:

$('hr[class^="line-rooms-sphere"]');
网友答案:

There should be no space between "hr" and "[class... ]" in the selector "$('hr [class^="line-rooms-sphere"]'". Check this snippet.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


    <hr class="line-rooms-sphere-4 rooms-hidden"/>

    <hr class="line-rooms-sphere-4 rooms-hidden"/>

    <hr class="line-rooms-sphere-4 rooms-hidden"/>


    <script>
    $(document).ready(function(){
      
      $('hr[class^="line-rooms-sphere"]').css("border-width","8px");
      
     });

    </script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: