开发者

Jquery getting ul depending a match in the child text in an anchor inside with variable value

开发者 https://www.devze.com 2023-01-27 10:40 出处:网络
I have the following javascript variable: <script> var theme=\"Videocameras\"; </script> And the following html code:

I have the following javascript variable:

<script>
   var theme="Videocameras";
</script>

And the following html code:

<div>    
     <span>Tecnology</span>
     <ul id="menu">
         <li>
            <a href="#">Multimedia</a>
            <ul>
                <li>
                    <a href="#">Videocameras</a>
                </li>

                <li>
                    <a href="#">Cameras</a&g开发者_运维问答t;
                </li>

                <li>
                    <a href="#">MP3 and MP4</a>
                </li>                  
            </ul> 
        </li> 
            <li>
            <a href="#">Telephony</a>
            <ul>              
                <li>
                    <a href="#">Mobile Phones</a>
                </li>

            </ul> 
        </li> 
     </ul>
</div>

I would like to know how to get a unique ul that has inside an href with text that matches to the value of the variable.

Could you give me a hand? Best Regards.


You can use :contains and .closest()

Try this

 $("a:contains(" + theme + ")").closest("ul");

See a working demo


@rahul's solution should work for you, but :contains is a check to find the text anywhere within that element's text. If you want a more robust solution, something like this would work:

$("#menu li > a").filter(function () { 
    return $(this).text() == theme; 
}).closest("ul");

Working demo: http://jsfiddle.net/AndyE/zU7bU/1/ (based on @rahul's fiddle)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号