Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access item inside div through javascript

I have a div which contain other tags inside it

<div id="mainDiv">
    <div>
        <table>
            <tbody>
                   <tr>
                      <td>1</td>
                      <td>item</td>
                      <td>item</td>
                      <td>2</td>
                   </tr>
            </tbody>
        </table>
    </div>

    <div>
        <table>
            <tbody>
                   <tr>
                      <td>1</td>
                      <td>item</td>
                      <td>item</td>
                      <td>5</td>
                   </tr>
            </tbody>
        </table>
    </div>
</div>

How can I access <td> of this mainDiv through javascript. I want to change innerHTML of these <td>

like image 860
Muhammad Imran Tariq Avatar asked Aug 15 '11 11:08

Muhammad Imran Tariq


People also ask

How do I get text in a div?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.

How do you target an element in JavaScript?

To select a specific HTML class using JavaScript, we need to target it and then store it as a variable. Here is the one line of JavaScript we need to target this element and store it as a variable: Code from a text editor: const vanillaDescription = document. querySelector('.

How do I get all elements of tag div inside HTML?

In this article, we will find how to get all elements of a specific class inside an HTML div tag. To do this we will use HTML DOM querySelectorAll()method. This method of HTML DOM (document object model) returns all elements in the document that matches a specified CSS selector(s).

Can we have script inside div?

You can add <script></script> inside a DIV tag. Just check on w3c, it is valid HTML.


1 Answers

var allDivTd = document.getElementById("mainDiv").getElementsByTagName("TD");

for(var i = 0; i < allDivTd.length; i++){
    var td = allDivTd[i];
    td.innerHTML = // do something w/ inner html
}
like image 79
Brian Avatar answered Sep 19 '22 16:09

Brian