简体   繁体   中英

how to disable anchor tag if href is empty in javascript

i have n number of anchor tags , if any anchor tag href is " undefined " then remove that particular a tag href attribute..

i tried if method but it removes all anchor tag href.

 (function () { if ((readMore.href = "undefined")) { readMore.removeAttribute("href"); } })();

here is the type of href value if their is no value in href在此处输入图像描述

If you want to check if the href attribute has as value the string "undefined" , then use == or === as @Nick Parsons suggests. But it might be also the browser who's interfering, because if you try with developer tools in Chrome and change a href attribute to the string "undefined" you actually would get something like "https://stackoverflow.com/undefined" which is a totally different string.

在此处输入图像描述

If you check the value in the console, you get: 在此处输入图像描述

where $0 refers to the element in the first screenshot.

If you want to check if the href attribute has falsy value like undefined, null or empty string , you'd write something like if (.readMore.href) .

The code you provide would just assign the string "undefined" to the href attribute which actually evaluates to true when put in if statement , that's why it happens for all items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM