2016-11-11 43 views
-1

我有这样的HTML:的JavaScript发现像jQuery的.find元素()

<div class="parent"> 
    <div></div> 
    <p> 
     <img src="#" widht="500"> 
    </p> 
</div> 

我需要的是让img width属性的值,但与普通的JavaScript。

我的JS:

window.onload = function(){ 
     var width = document.querySelector('.parent > p > img').getAttribute('width'); 
     var img = document.querySelector('.parent > p > img'); 
     img.style.width = width+'px'; 
    }; 

但我仍然得到这个错误:

Uncaught TypeError: Cannot read property 'getAttribute' of null 

所以,img没有找到我想..我怎样才能从img.parentdiv找到?

+3

在HTML'宽度'拼写错误 –

+1

代码应该可以正常工作,只需测试它与修正的错字。 – epascarello

+0

好吧,那么它是如何发生的我收到这个错误?不适合我吗? – EBuzila

回答

0

Uncaught TypeError: Cannot read property '.getAttribute()' of null

这意味着document.querySelector('.parent > p > img')返回NULL,我不知道为什么,因为你调用window.onload里面的脚本,所以如果你在同一HTML/JS张贴在OP,刚修好的错字width在你的HTML代码,以便:

<img src="#" widht="500"> 
_____________^^^^^ 

应该是:

<img src="#" width="500"> 

那么你的代码应按照您可以在下面的例子中看到。 希望这有助于。

window.onload = function(){ 
 
    var width = document.querySelector('.parent > p > img').getAttribute('width'); 
 
    var img = document.querySelector('.parent > p > img'); 
 
    img.style.width = width+'px'; 
 

 
    console.log(width); 
 
    console.log(img.style.width); 
 
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 
 
<div class="parent"> 
 
    <div></div> 
 
    <p> 
 
     <img src="#" width="500"> 
 
    </p> 
 
</div>

+0

我实际上在这个例子上拼写错误...而且我得到的错误就像img没有找到... – EBuzila

+0

你可以检查我更新的答案,并注意到脚本获得'width'。 –

0

你只需要与img属性width固定错字,并可以直接img.width访问:

var img = document.querySelector('.parent > p > img'); 
 
console.log('Width:', img.width);
<div class="parent"> 
 
    <div></div> 
 
    <p> 
 
     <img 
 
      src="http://static.adzerk.net/Advertisers/f380ecc42410414693b467ac7a97901b.png" 
 
      width="500"> 
 
    </p> 
 
</div>