Andy Thomas
Andy Thomas

Reputation: 79

How to find and add the function to id?

I want to add a function to the attribute onChange of the element with id="custom-taxonomy". I don't want to edit the file. I want to have a javascript solution.

My idea is to find the element by the id and then add the function. How can i achiev this idea?

The code:

<div id ="custom-taxonomy">PRODUCT PRICES</div>

Expected result:

<div id ="custom-taxonomy" name="custom-product" onchange="return chothuephuongxa();>PRODUCT PRICES</div>

Upvotes: 0

Views: 67

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

you can do that using setAttribute() and document.getElementById

let elm = document.getElementById('custom-taxonomy')
elm.setAttribute('name',"custom-product")
elm.setAttribute("onclick","return chothuephuongxa();")
console.log(elm.outerHTML)
<div id ="custom-taxonomy">PRODUCT PRICES</div>

Note:

  • You can't use name attribute of <div> but using elm.name = ... because name property in not available on <div> elements.
  • Similarly elm.onclick = "return chothuephuongxa();" is not correct because this will set event to string instead of function

Upvotes: 1

Script47
Script47

Reputation: 14540

You can use setAttribute to add attributes to elements:

document.getElementById('custom-taxonomy').setAttribute('name', 'custom-product');

the same can be done for your event.

Upvotes: 0

Related Questions