Javascript DOM Style Set Paragraph background

Description

Javascript DOM Style Set Paragraph background

View in separate window

<!DOCTYPE html>
<head>
<style>
div{//from ww w.j  av a  2 s  .  c  om
  padding: 10px;
  border: 1px solid #000000;
}
</style>
<script type="text/javascript">

window.onload=function() {
   document.onclick=function() {
     try {
      let paras = document.querySelectorAll('div p:first-of-type');
      for (let i = 0; i < paras.length; i++) {
         paras[i].setAttribute("style","background-color: #ffff00");
      }
     } catch(e) {
       let divs = document.querySelectorAll("div");
       for (let j = 0; j < divs.length; j++) {
          let ps = divs.item(j).getElementsByTagName("p");
          if (ps.length > 0) {
             ps[0].setAttribute("style","background-color: #ffff00");
          }
        }
     }
   }
}
</script>
</head>
<body>
  <div>
     <p>Paragraph one</p>
     <p>Paragraph two</p>
     <p>Paragraph three</p>
  </div>
  <div>
     <p>Paragraph one</p>
     <p>Paragraph two</p>
  </div>
  <div>
     <ul>
        <li>List item one</li>
        <li>List item two</li>
     </ul>
     <p>Paragraph one</p>
     <p>Paragraph two</p>
  </div>
</body>
</html>



PreviousNext

Related