Wednesday 15 May 2013

I can't use jQuery library, and I am getting TypeError: document.getElementById(...) is null when 'translating' to pure javascript -


I am unable to use the jQuery library on my project, so I have this small jQuery snippet 'Pure' javscript

  $ (document) .ready (function () {$ listHeight = $ ('ul # home-news-list') height (); $ child = $ ('ul # home-news Lilly Lee: $ ($ List High> 150) {$ ($ Child) .remove (); $ listHeight = $ ('# home-news-inner ul'). Height (); $ child = $ (' Ul #home-news-catalog li: last-child '); console.log ($ listHeight);}});   

The list list height is less than 150, as long as it basically removes the last list item. My Javascript skill is not good, so this is the code that I came up with and it gives me TypeError: document.getElementById (...) is zero on the first line, so I do not know Everything else is worth:

  var listHeight = document.getElementById ('home-news-list') offsetHeight () .; Var children = document.getElementById ('home-news-list li: last-child'); While (listHeight> 150) {child.parentNode.removeChild (child); Var listHeight = document.getElementById ('Home-News-List'). OffsetHeight (); Child = document.getElementById ('home-news-list li: last-child'); }   

Can you please tell me what is wrong with the code?

I use this script as & lt; Head & gt; & Lt; / Head & gt; / C>

If you want to use CSS selectors such as jquery, then you can get javascript query selector And use the queryciter. Methods

  var listHeight = document.getElementById ('home-news-list'). OffsetHeight (); Var child = document.query selector ('home-news-list li: last-child'); While (listHeight> 150) {child.parentNode.removeChild (child); Var listHeight = document.getElementById ('Home-News-List'). OffsetHeight (); Child = document.query selector ('home-news-list li: last-child'); }   

This is similar to your code but replaced with querySelector when getElementByid does not work.

No comments:

Post a Comment