2016-11-11 11 views
-1

私はこのHTMLを持っています。JavaScriptはjQueryの.findのような要素を見つける()

マイ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から見つけることができますどのように..推測見つかりませんか? document.querySelector('.parent > p > img')リターンヌルを意味

+3

'幅を'は間違って綴られています –

+1

コードはうまく動作するはずです。ちょうどタイプミスを修正してテストしました。 – epascarello

+0

それでは、どのようにエラーが発生しますか?私のために働かない? – EBuzila

答えて

0

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

あなたは同じHTML/JSだけでタイプミスを修正し、OPに掲載しましたので、もし、私は、あなたがwindow.onload内のスクリプトを呼び出している理由ので、わからない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>
あなたのHTML内

関連する問題