Javascript Add class & id to Table Element (JACITE)

Hi bro, sorry I had a misunderstanding when trying out random codes to apply the technique of adding class name and id to each html tag dynamically using javascript, but it still failed. The actual case study is that I want to add the class name and id to a table cell or in other words I want to add the attribute to the <td> tag. Can you guys enlighten me with a simple example? Thank you.

Solution

You can use,

Element.setAttribute(name, value);

Description: sets the value of an attribute on the specified element. If the attribute already exists, its value is updated; otherwise, a new attribute is added with the specified name and value.

In other cases, you can also get the value of an existing attribute by using getAttribute(); while to delete an attribute you can use removeAttribute();

Okay, now back to your case study, here is a simple example.

var td1 = document.createElement('td');
var td2 = document.createElement('td');

td1.setAttribute('class', 'className');
td2.setAttribute('class', 'className');

Hope it is useful!


Post a Comment

Previous Next

نموذج الاتصال