javascriptjqueryhtmljquery-tags-input

jQuery add class to children of a tag and children of children of all the tags


I need to add a class to all the following tags. The sample JS I have included only adds the class to the direct children tags

before

<div name='myDiv'>
    <fieldset>
        <div><input>exmaple</input></input></div>
    </fieldset>
</div>

jQuery:

$("[name='myDiv']").children().addClass("myClass");

after

<div name='myDiv'>
    <fieldset class="myClass">
        <div><input>exmaple</input></input></div>
    </fieldset>
</div>

However, the following is the expected result:

<div name='myDiv'>
    <fieldset class="myClass">
        <div class="myClass"><inputclass="myClass">exmaple</input></input></div>
    </fieldset>
</div>

Solution

  • use * . see snippet below

    P.S. input tags do not need to be closed with </input> . you can add a label associated to them if you want

    $("[name='myDiv'] *").addClass("myClass");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div name='myDiv'>
        <fieldset>
            <div><input>exmaple</div>
        </fieldset>
    </div>