JavaScript找到像jQuery这样的元素.find()

时间:2016-11-11 15:04:08

标签: javascript html

我有这个HTML:

<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 .parent找到div

2 个答案:

答案 0 :(得分:0)

  

未捕获的TypeError:无法读取null的属性'.getAttribute()'

这意味着document.querySelector('.parent > p > img')返回null,我不确定为什么因为你在window.onload内调用脚本,所以如果你在OP中发布了相同的HTML / JS,那么修复HTML代码中的拼写错误width

<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>

答案 1 :(得分: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>