Prepare for Angular Interviews with real-life questions. Utilize quizzes and examples to deepen understanding and enhance your skills. Gear up to ace your interview!

Each practice test/flash card set has 50 randomly selected questions from a bank of over 500. You'll get a new set of questions each time!

Practice this question and more.


Which method is used to update an HTML attribute?

  1. element.propertyName = 'value'

  2. document.createAttribute()

  3. element.setAttribute('attributeName', 'value')

  4. getAttribute('attributeName')

The correct answer is: element.setAttribute('attributeName', 'value')

The method used to update an HTML attribute in the DOM is through the `setAttribute` function. This method directly modifies the specified attribute of an HTML element by replacing its current value with a new one. It takes two parameters: the name of the attribute you want to change and the new value you wish to assign to it. For instance, if you have an `<img>` element and you intend to change its `src` attribute, you can do this by invoking `element.setAttribute('src', 'newImagePath.jpg')`. This action effectively updates the displayed image to the new source. The other methods mentioned serve different purposes. While `element.propertyName = 'value'` can change certain properties associated with HTML elements, it does not universally apply to attributes — the property may not reflect the corresponding attribute if they differ. `document.createAttribute()` is used to create an attribute object but does not attach it to any element, making it ineffective for updating attributes directly. The `getAttribute('attributeName')` method is aimed at retrieving the value of a specified attribute rather than modifying it, hence it does not serve the function of updating an attribute.