get the style of a cached dom element using .find()

时间:2017-08-05 11:39:47

标签: javascript jquery html

i cached a <div> in an object, and i want to use .find() method to get its style property without touching the DOM

lets say:

    <body>
      <div id="one" style="visibility:visible;">
       </div>
     </body>

   <script>
        var cache = {
             cacheBody: $("body").find("div#one")
            } 
     //i want to do this 
      chach.cacheBody.find("style") //or chach.cacheBody.find("visibilty")
    </script>

the importent thing is that, i dont want to use jquery on DOM for this.

but on the cached object

2 个答案:

答案 0 :(得分:1)

I believe your use of .find() here is incorrect. It is used to traverse the DOM and "find" nodes that match the parameter given.

What you may be after is .attr(). If you want to get the style specific to that DOM Node which was given inline. Otherwise if you want the entire CSSStyleDeclaration object, you can use:

$('div#one')[0].style // instead of $('div#one').attr('style')

To get a complete object of all applied (and not applied) styles to the Node.

This is not as browser compatible as the rest of the code as it does not make use of jQuery for retrieving the actual object.

答案 1 :(得分:0)

var cache = {
             cacheBody: $("div#one")
            } 
     //i want to do this 
   var style=   cache.cacheBody.attr("style"); //or chach.cacheBody.find("visibilty")
   console.log(style);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one" style="visibility:visible;">
       </div>