How to change element html properties on click?

Member

by shyann , in category: HTML & CSS , a year ago

How to change element html properties on click?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , a year ago

@shyann 

To change an element's HTML properties on click, you can use JavaScript or jQuery. Here's an example using JavaScript:

  1. HTML: Add an element with an onclick attribute:
1
<p id="myElement" onclick="changeProperties()">Click me</p>


  1. JavaScript: Define a function to change the properties of the element:
1
2
3
4
5
6
function changeProperties() {
  var element = document.getElementById("myElement");
  element.innerHTML = "Text changed";
  element.style.color = "red";
  // Add more property changes as needed
}


Now, when you click on the element with the id "myElement", the function changeProperties() will be called. It will then change the innerHTML of the element to "Text changed" and its font color to red.


Note: You can change any property of an element using this method. The element.style object allows you to modify CSS properties such as color, background-color, font-size, etc.


If you prefer using jQuery instead of plain JavaScript, the code would look like this:

  1. HTML: same as above
  2. jQuery: Define a function to change the properties of the element using jQuery methods:
1
2
3
4
5
6
function changeProperties() {
  var element = $("#myElement");
  element.text("Text changed");
  element.css("color", "red");
  // Add more property changes as needed
}


Both approaches achieve the same result, but the jQuery version has a simpler syntax and provides additional utility functions.