How to Access HTML Parameters in JavaScript?

Estimated read time 2 min read

To access HTML parameters (also known as attributes) in JavaScript, you can use the getAttribute() method of the element.

Here’s an example of how to get the value of the src attribute of an img element using JavaScript:

<img src="example.jpg" alt="Example image" id="myImage">
// Get the img element by its ID
var myImage = document.getElementById("myImage");

// Get the value of the src attribute
var imageSrc = myImage.getAttribute("src");

// Log the value of the src attribute
console.log(imageSrc);

In this example, we first use the getElementById() method to get the img element with the ID of “myImage”, and assign it to the myImage variable. We then use the getAttribute() method to get the value of the src attribute of the myImage element, and assign it to the imageSrc variable. Finally, we use console.log() to log the value of the imageSrc variable to the console.

You can use the getAttribute() method to get the value of any attribute on an element, such as class, id, href, data-*, etc. Just pass the name of the attribute as a string argument to the method. If the attribute is not present on the element, getAttribute() will return null.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply