Skip to main content

Attributes / Properties

Browser Document: Attributes / Properties



What happens to the HTML when the browser loads the page?

View Answer:
Interview Response: The browser fetches the HTML, parses it into the Document Object Model (DOM), applies CSS styles, runs JavaScript, and then renders the final visual representation on the screen.

What is the difference between attributes and properties in JavaScript?

View Answer:
Interview Response: Attributes are defined on HTML elements and represent the initial state. Properties are in DOM objects, reflecting the current state of elements and can change over time.

Can you modify or customize a DOM node?

View Answer:
Interview Response: Yes, you can modify a DOM node. JavaScript allows you to change content, attributes, CSS styles, and even add or remove nodes to and from the DOM tree.

Technical Response: Because DOM nodes are ordinary JavaScript objects, we can modify them just like any other object. This object may change or add methods and attributes, as well as edit built-in prototypes such as Element.prototype and add new methods to all elements.

Code Example:

// Property Creation
document.body.myData = {
name: 'Caesar',
title: 'Imperator',
};

console.log(document.body.myData.title); // Imperator

// Add new method
document.body.sayTagName = function () {
console.log(this.tagName);
};

document.body.sayTagName();
// BODY (the value of "this" in the method is document.body)

// Add new method to all Elements
Element.prototype.sayHi = function () {
console.log(`Hello, I'm ${this.tagName}`);
};

document.documentElement.sayHi(); // Hello, I'm HTML
document.body.sayHi(); // Hello, I'm BODY

note

DOM properties and methods behave just like those of regular JavaScript objects. They can have any value and are case-sensitive (write elem.nodeType, not elem.NoDeTyPe).


How can you get the value of an attribute in JavaScript?

View Answer:
Interview Response: You can get the value of an attribute using the `getAttribute()` method on the element, passing the attribute name as the argument.

How can you set an attribute value in JavaScript?

View Answer:
Interview Response: You can set an attribute value using the `setAttribute()` method on the element, passing the attribute name and the new value as arguments.

How do you remove an attribute from an HTML element in JavaScript?

View Answer:
Interview Response: You can remove an attribute using the `removeAttribute()` method on the element, passing the attribute name as the argument.

What is the role of the "className" property in JavaScript?

View Answer:
Interview Response: The `className` property gets or sets the value of the `class` attribute, allowing you to manipulate CSS classes of an element.

What is the "dataset" property in JavaScript?

View Answer:
Interview Response: The `dataset` property is an object that holds all the custom data attributes (`data-*`) of an element, allowing easy access and manipulation.

How can you modify the "src" attribute of an "img" element in JavaScript?

View Answer:
Interview Response: To modify the `src` attribute, you can use the `setAttribute()` method or directly update the `src` property of the `img` element.

Do different elements have different standard HTML attributes?

View Answer:
Interview Response: Yes, different HTML elements have different standard attributes. For example, an "img" tag has "src" and "alt", while an anchor "a" tag has "href" and "target" attributes. We should note that a standard attribute for one element can be unknown for another. An example is the input element with a standard type attribute used to specify the input type.

Code Example:

<body id="body" type="...">
<input id="input" type="text" />
<script>
console.log(input.type); // text
console.log(body.type);
// undefined: DOM property not created, because it is non-standard
</script>
</body>

note

The "type" attribute is standard for input (HTMLInputElement), but not for body (HTMLBodyElement). Standard attributes are described in the specification for the corresponding element class. So, if an attribute is non-standard, there will not be a DOM-property for it.


What happens to non-standard attributes when the browser loads the page? Does it become a DOM property like standard element attributes?

View Answer:
Interview Response: Non-standard attributes don't become DOM properties directly, but they can be accessed via the "getAttribute" method or dataset for data-* attributes. They don't affect rendering unless used by JavaScript or CSS.

Technical Response: In HTML, tags may have attributes. When the browser parses the HTML to create DOM objects for tags, it recognizes standard attributes and creates DOM properties from them. In the case of non-standard attributes, DOM properties are created, and any invocation of those attributes returns undefined.

The attribute exists, but it does not get defined as DOM property, which inevitably returns undefined.

Code Example:

<body id="test" something="non-standard">
<script>
console.log(document.body.id); // test
// non-standard attribute does not yield a property
console.log(document.body.something); // undefined
</script>
</body>

Is there a way to access non-standard HTML attributes?

View Answer:
Interview Response: Yes, you can access non-standard HTML attributes using JavaScript's "getAttribute" method or the "dataset" property for data-* attributes on the corresponding DOM object.

Technical Response: Yes, various JavaScript methods, such as hasAttribute, getAttribute, setAttribute, and removeAttribute, are used to access non-standard HTML attributes. These approaches work with precisely what is written in HTML. Additionally, elem.attributes may be used to read all attributes: a collection of objects that belong to the built-in Attr class, containing name and value properties.

Code Example:

<body something="non-standard">
<script>
console.log(document.body.getAttribute('something')); // non-standard
</script>
</body>

What are the two primary features of HTML attributes?

View Answer:
Interview Response: All HTML attributes have two essential features. Their name is case-insensitive (id is the same as ID), and their values are always strings.

Code Example:

<body>
<div id="elem" about="Elephant"></div>

<script>
console.log(elem.getAttribute('About')); // (1) 'Elephant', reading

elem.setAttribute('Test', 123); // (2), writing

console.log(elem.outerHTML); // (3), see if the attribute is in HTML (yes)

for (let attr of elem.attributes) {
// (4) list all
console.log(`${attr.name} = ${attr.value}`);
}
</script>
</body>

View Answer:
Interview Response: When a standard attribute changes, the corresponding property is auto-updated, and vice versa, maintaining a synchronized state between them, but there are some exceptions to the rule. This behavior gets defined as property-attribute synchronization in JavaScript.

Code Example:

<input />

<script>
let input = document.querySelector('input');

// attribute => property
input.setAttribute('id', 'id');
console.log(input.id); // id (updated)

// property => attribute
input.id = 'newId';
console.log(input.getAttribute('id')); // newId (updated)
</script>

Can you name one exception to the rule of property-attribute synchronization?

View Answer:
Interview Response: One exclusion or exception is input.value can only synchronize from attribute to property, but not back. Changing the attribute value updates the property, but the property change does not affect the attribute.

Code Example:

<script>
let input = document.querySelector('input');

// attribute => property
input.setAttribute('value', 'text');
console.log(input.value); // text

// NOT property => attribute
input.value = 'newValue';
console.log(input.getAttribute('value')); // text (not updated!)
</script>

note

That “feature” may come in handy because the user actions may lead to value changes, and then after them, if we want to recover the “original” value from HTML, it is in the attribute.


Are DOM properties always strings like HTML attributes?

View Answer:
Interview Response: No, DOM properties are not always strings because they have property types. They can be different types like boolean, object, or function, depending on the property. For instance, "classList" is an object, "disabled" is a boolean. For instance, the input.checked property (for checkboxes) is a Boolean (either checked or not checked). There are other examples. The style attribute is a string, but the style property is an object. Most properties are strings, however.

Code Example:

<!-- CHECKBOX EXAMPLE -->
<input id="input" type="checkbox" checked />

<script>
console.log(input.getAttribute('checked')); // the attribute value is: empty string
console.log(input.checked); // the property value is: true
</script>

<!-- STYLE PROPERTY EXAMPLE -->
<div id="div" style="color:red;font-size:120%">Hello</div>

<script>
// string
console.log(div.getAttribute('style')); // color:red;font-size:120%

// object
console.log(div.style); // [object CSSStyleDeclaration]
console.log(div.style.color); // red
</script>

Can you describe a case for the use of non-standard attributes?

View Answer:
Interview Response: We can use non-standard attributes to pass custom data from HTML to JavaScript or “mark” HTML elements for JavaScript. Non-standard attributes, especially data-* attributes are used to store extra information directly within an HTML element for later use in JavaScript, without affecting the presentation or semantics.

Code Example:

<!-- mark the div to show "name" here -->
<div show-info="name"></div>
<!-- and age here -->
<div show-info="age"></div>

<script>
// the code finds an element with the mark and shows what's requested
let user = {
name: 'Pete',
age: 25,
};

for (let div of document.querySelectorAll('[show-info]')) {
// insert the corresponding info into the field
let field = div.getAttribute('show-info');
div.innerHTML = user[field]; // first Pete into "name", then 25 into "age"
}
</script>

Is it possible to style an element with non-standard HTML attributes?

View Answer:
Interview Response: Yes, we can use non-standard HTML attributes to style our elements. This change may be accomplished by acting on an element's class or id and modifying the styles. This approach works for both inline and external style sheets, and this is a much better way to handle the style based on the state of our elements.

Code Example:

<style>
/* styles rely on the custom attribute "order-state" */
.order[order-state='new'] {
color: green;
}

.order[order-state='pending'] {
color: blue;
}

.order[order-state='canceled'] {
color: red;
}
</style>

<div class="order" order-state="new">A new order.</div>

<div class="order" order-state="pending">A pending order.</div>

<div class="order" order-state="canceled">A canceled order.</div>

danger

We should note that this is not exactly the recommended approach for implementing custom attributes in HTML.


Is there a way to avoid conflicts when creating custom attributes?

View Answer:
Interview Response: Yes, to avoid conflicts, use the "data-*" prefix when creating custom attributes. This naming convention is specified by HTML standards for user-defined data attributes.

Technical Response: Yes, we should prepend custom attributes with the “data-*” attribute to avoid conflicts in your code. All attributes starting with “data-” are reserved for programmers’ use and available in the dataset property. The main reason to use the data attribute is if the standard attribute specification is updated. You can avoid any conflicts in your code. Using data-* attributes is a proper, safe way to pass custom data.

Code Example:

<body data-about="Elephants">
<script>
console.log(document.body.dataset.about); // Elephants
</script>
</body>

Are multi-word attributes case sensitive in dataset properties?

View Answer:
Interview Response: Yes, multi-word "data-*" attributes become camelCase properties in "dataset". For example, "data-my-attribute" becomes "dataset.myAttribute". HTML attributes are case-insensitive, but their dataset properties are not.

Code Example:

<style>
.order[data-order-state='new'] {
color: green;
}

.order[data-order-state='pending'] {
color: blue;
}

.order[data-order-state='canceled'] {
color: red;
}
</style>

<div id="order" class="order" data-order-state="new">A new order.</div>

<script>
// read
console.log(order.dataset.orderState); // new

// modify
order.dataset.orderState = 'pending'; // (*) camel case dataset property
</script>