Html clear img src

Html clear img src

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Clear Img src attribute using JavaScript

To clear an image src attribute:

  1. Use the setAttribute() method to set the image’s src attribute to an empty string.
  2. Alternatively, hide the image element.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> img id="img" src="https://example.com/does-not-exist.jpg" alt="banner" /> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const img = document.getElementById('img'); // 👇️ set image src attribute to an empty string img.setAttribute('src', ''); // 👇️ or hide image img.style.display = 'none';

We used the setAttribute method to set the src attribute of the image element to an empty string.

However, if you do that the image is still displayed as being broken.

Alternatively, you can hide the image by setting its display property to none .

We used the display property to hide the image element, however, you might need to use the visibility property, depending on your use case.

When an element’s display property is set to none , the element is removed from the DOM and does not affect the layout. The document is rendered as though the element does not exist.

On the other hand, when an element’s visibility property is set to hidden , it still takes up space on the page, however, the element is invisible (not drawn). It still affects the layout of your page as normal.

# Clear Img src attribute using the visibility property

Here is an example that sets the image’s visibility property to hidden .

Copied!
const img = document.getElementById('img'); // 👇️ set image src attribute to an empty string img.setAttribute('src', ''); // 👇️ or hide image img.style.visibility = 'hidden';

When the image’s visibility is set to hidden , it is invisible, however, it still takes up space on the page.

If you set the image’s display property to none , the element is removed from the DOM and other elements take its space.

# Clear Img src attribute using removeAttribute

You can also use the removeAttribute method to clear the image’s src attribute.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> img id="img" src="https://example.com/does-not-exist.jpg" alt="banner" /> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const img = document.getElementById('img'); // 👇️ set image src attribute to an empty string img.removeAttribute('src'); // 👇️ or hide image img.style.display = 'none';

The Element.removeAttribute method removes the attribute with the specified name from the element.

If you don’t want to move the elements on the page when hiding the image, use the visibility property instead.

Copied!
const img = document.getElementById('img'); // 👇️ set image src attribute to an empty string img.removeAttribute('src'); // 👇️ or hide image img.style.visibility = 'hidden';

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Check if a Window or a Browser Tab has Focus in JavaScript
  • Clear the Content of a Div element using JavaScript
  • Clear Input fields after Submit using JavaScript
  • How to Clear an Object in JavaScript
  • How to Clear Text Selection using JavaScript
  • Clear the Value of a Textarea using JavaScript
  • Clone an Element and change its ID using JavaScript
  • How to change the href of an anchor tag using JavaScript
  • How to replace plain URLs with links using JavaScript
  • Refresh an image with a new one at the same URL using JS
  • How to Get the information from a meta tag using JavaScript
  • Disable drag and drop on HTML elements using JavaScript
  • Disable text selection on Double-click in CSS or JavaScript
  • console.log() not working in JavaScript & Node.js [Solved]
  • How to save an image to localStorage using JavaScript
  • Set background-image as a base64 encoded image in JavaScript
  • How to Preview an image before uploading in JavaScript
  • How to store an Array or Object in localStorage using JS
  • The JavaScript equivalent to PHP Echo/Print statements

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Clear img src Attribute Using JavaScript

While designing an interactive web page or site, there can be a requirement to transition between various elements from time to time. For instance, in the process of adding captcha and image recognition techniques or hiding a particular element for the appropriate utilization of the Document Object Model(DOM). In such cases, clearing img src attribute is beneficial in ensuring the accessible document design and making the site stand out.

This blog will explain how to clear the image src attribute using JavaScript.

How to Clear img src Attribute Using JavaScript?

To clear the img src attribute using JavaScript, the following approaches can be utilized:

Let’s follow each of the approaches one by one!

Approach 1: Clear img src Attribute in JavaScript Using removeAttribute() Method

The “removeAttribute()” method removes the attribute from an element. This method can be utilized to clear a particular attribute resulting in removing the specified image upon the button click.

Let’s follow the below-stated example:

In the above code snippet:

    • Specify the stated image having the specified “id” and the “src” attribute.
    • Also, create a button with an attached “onclick” event invoking the clearAttribute() function.
    • In the JavaScript code, define a function named “clearAttribute()”.
    • In its definition, access the included image via “id” using the “getElementById()” method.
    • Finally, apply the “removeAttribute()” method to remove the “src” attribute, which will result in clearing the image upon the button click.

    The above output signifies that the image specified in the “src” attribute clears upon the button click.

    Approach 2: Clear img src Attribute in JavaScript Using display Property

    The “display” property returns the display type of the associated element. This property can be utilized to assign a value to the corresponding element such that the contained attribute is cleared upon the button click.

    Let’s overview the following example:

    In the above lines of code, implement the following steps:

      • Recall the approaches for including an image via the “src” attribute and creating a button having an “onclick” event.
      • In the JavaScript code, define the function “clearAttribute()”.
      • In its definition, similarly, access the included image using the “getElementById()” method.
      • Lastly, assign the value “none” to the display property. This will result in clearing the image specified in the “src” attribute.

      The above output indicates that the desired functionality is achieved.

      Approach 3: Clear img src Attribute in JavaScript Using visibility Property

      The “visibility” property assigns the value such that an element becomes visible or not. This property can be implemented to hide the associated element, thereby disabling the image specified in the “src” attribute within the element.

      The below-given example illustrates the stated concept:

      In the above lines of code:

        • Likewise, specify the stated image having the specified “id” and the “src” attribute.
        • Also, associate an “onclick” event with the created button redirecting to the clearAttribute() function.
        • In the JavaScript part of the code, define a function named “clearAttribute()”.
        • Here, similarly, access the included image using the “getElementById()” method.
        • Finally, assign the value “hidden” to the associated element, i.e., image.
        • This will resultantly hide the image specified in the “src” attribute, thereby clearing it upon the button click.

        The specified image is cleared from DOM upon the button click, thereby clearing the “src” attribute.

        Conclusion

        The “removeAttribute()” method, the “display” property, or the “visibility” property can be applied to clear img src attribute using JavaScript. The removeAttribute() method can be utilized to remove the ”src” attribute which will result in clearing the specified image in it as well. The display property hides the display thereby clearing the image upon the button click. The visibility property hides the associated element resulting in clearing the contained “src” attribute as well. This blog is guided to clear the img src attribute in JavaScript.

        About the author

        Umar Hassan

        I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.

        Источник

        Как установить изображение src пустым? [Дубликат]

        Пустая строка на самом деле может быть допустимым src для изображения, технически говоря, это не «удаление» src. Так же, как # , он будет использовать текущий URL плюс хеш. Реальный пример: lcamtuf.coredump.cx/squirrel В итоге вы отправите запрос на текущий URL. Я бы предложил использовать другой подход.

        3 ответа

        Поскольку у вас есть селектор id. Использование собственного метода javascript document.getElementById даст вам больше преимуществ в производительности. Также вам может потребоваться установить # как src вместо строки empty .

        document.getElementById('img').src = "#"; 

        Боюсь, это не сработает. По-прежнему указывает на текущий URL вместо того, чтобы иметь пустое значение.

        Я просто получил бы доступ к подстилке node и установил значение src в пустую строку.

        Обновление. Кажется, что Chrome не удовлетворен, когда мы просто передаем пустую строку. Firefox по-прежнему показывает ожидаемое поведение (я уверен, что это также работало в Chrome пару недель/версий назад).

        Однако, например, передача # выполняется нормально.

        Даже imgNode.removeAttribute(‘src’); больше не удаляет визуальное изображение изображения в Chrome (интересно. ).

        Боюсь, это не сработает. По-прежнему указывает на текущий URL вместо того, чтобы иметь пустое значение.

        @TimmyO’Tool: TimmyO’Tool: действительно. Странное поведение, которое мне кажется «новым». Тем не менее, это работает, если вы передаете, например, # .

        Пустая строка на самом деле может быть допустимым src для изображения, технически говоря, это не «удаление» src. Так же, как # , он будет использовать текущий URL плюс хеш. Реальный пример: lcamtuf.coredump.cx/squirrel В итоге вы отправите запрос на текущий URL.

        Атрибут ‘src’ на самом деле не является свойством, это атрибут. Подумайте о свойствах как о вещах, которые могут быть заданы с булевыми или списками и атрибутами как вещи, которые намного более динамичны.

        Источник

        Читайте также:  Выравнивание
Оцените статью