Search code examples
htmlattributestablehtml

Add attribute to dynamicaly created table


Helo,

I'm working with external software which is generating reports. I'm getting table, then it is printed to website in div. I don't have access to this table before it is generated, so i can't set any attribute before website is rendered.

So I need to add attribute to this table as last step of rendering process, it doesn't matter is it ID or Class.

Structure is like:

 <div class="data" id="Checklist">
     <p>Some text</p>

     <!-- There is this table -->
     <table style="...">...</table>

     <p></p> 
 </div>

I'm using IE v11.

I tried something like this (nothing happens):

  document.getElementById("Checklist").childNodes[0].className = "TestClassName";

Also (it gives mi error: Object doesn't support property or method 'setAttribute' )

 document.getElementById('news').childNodes[0].setAttribute( 'class', new_class );

Any other ideas?


Solution

  • If you use ChildNodes it will return all the white space with nodelist so use children so that it will return only child elements

    <div class="data" id="Checklist">
         <p>Some text</p>
    
         <!-- There is this table -->
         <table style="...">...</table>
    
         <p></p> 
     </div>
    

    Change Your js to

    document.getElementById("Checklist").children[0].className="TestClassName";
    document.getElementById('news').children[0].setAttribute( 'class', new_class );
    

    it will work