Home > Software engineering >  Select/edit all children elements inside a div
Select/edit all children elements inside a div

Time:02-25

How can I use jquery or css to assign a .class to all elements inside a div?

i.e this is what I have

<div >
   <a href="">one</a>
   <a href="">two</a>
</div>

But this is what I want

<div >
   <a href="" >one</a>
   <a href="" >two</a>
</div>

Using as little code as possible, so that when the page loads, the elements in .nav have the class "test" assigned to them and I don't have to assign it in every single

CodePudding user response:

You can achieve this by following code

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>
        <div>
            <a href="">one</a>
            <a href="">two</a>
        </div>
    </body>
    <script type="text/javascript">
        $(document).ready(function () {
            $('div > a').addClass('test')
        })
    </script>
</html>

CodePudding user response:

Pretty simple in jQuery: $('div a').addClass('class');

Or in JavaScript something like this:

let links = document.querySelectorAll("div a");

for(let link of links) {
  link.classList.add("class");
}
.class {
  text-decoration: none;
  color: orange;
  font-size: 50px;
  margin-right: 100px;
}
<div >
   <a href="">one</a>
   <a href="">two</a>
</div>

CodePudding user response:

$(document).ready(function() { $('.nav a').each(function(){ $(this).addClass("Test"); }) });
.Test{
color:red
}
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div >
        <a href="">one</a>
        <a href="">two</a>
    </div>

  • Related