acces.htmlというページ以外で演算子を使用してacces.htmlでない場合以下の処理を行いたかったのですが、acces.htmlでconsoleエラーが表示されてしまい。解消したく、レクチャー頂ければ幸いです。
※querySelector取得してるclinic_infoという要素はacces.htmlは存在しません、。
window.addEventListener('DOMContentLoaded', () => { let url = location.pathname; if (url !== "acces.html") { const targetElement = document.querySelector('.clinic_info'); const elm = document.createElement('div'); elm.classList.add('js-mt70'); targetElement.insertAdjacentElement('beforebegin',elm); } //console.log(location.pathname) });
エラーメッセージ
utils.js:322 Uncaught TypeError: Cannot read properties of null (reading 'insertAdjacentElement')
内容追記します。
acces.html以外のページにはclinic_infoというクラス名のdivタグが存在します。
こちらにjsでcreateElementでdivタグを生成し、クラス名js-mt70を付与して、clinic_infoの上に出力させます。
※やりかたがイケてない等あると思いますが、こちらでは無視してください。
<div class="js-mt7"></div> <div class="clinic_info">text</div>
acces.htmlにはclinic_infoのdivタグが存在しないHTMLとなります。
acces.html以外はclinic_infoがあるので、acces.htmlでない場合はif文の処理を実行し、現在表示されてるコンソールエラーを解消したかったのです。
※恐らくclinic_infに対してinsertAdjacentElementしているのがエラーの原因かと思い。
※回答沢山ありがとうございました。
これから確認させていただきます。