Show child elements html and js

5

I would like to know how I can only show the child elements with javascript for example.

<div class="row">
    <span class="red">66 
        <span>22 </span>
    </span>
    <span class="green">24
        <span class="blue" style="color: #000;">82 </span>
    </span>
    <span class="green">10 
        <span class="blue" style="color: #000;">1 </span>
    </span>
    <span class="red">69 
        <span>80 </span>
    </span>
    <span class="red">12 
        <span class="green" style="color: #000;">11 </span>
    </span>
 </div>

I would just like to show the "span" children

I have done something like that but it does not work and I do not know how to shape it

function myFunction6() {
var foo = document.getElementsByTagName('span');
for (var i = 0; i < foo.children.length; i++) {
        console.log(foo.children[i].tagName);
}
}

Thanks

    
asked by Rafa Alvarez-Ossorio Martin 14.05.2018 в 22:27
source

2 answers

7

If you want to keep only the span that are inside another span on the div with class .row , I would recommend that you use a different selector of getElementsByTagName . For example, it would be more convenient to use querySelectorAll .

To that function you pass a selector like CSS and it will return all the elements that meet that condition. For example, with the .row > span > span selector, what you are going to obtain are all span elements that are direct children of another span and that are within .row . Here you can see it working:

function myFunction6() {
  var foo = document.querySelectorAll('.row > span > span');
  for (var i = 0; i < foo.length; i++) {
    console.log(foo[i].tagName + " " + foo[i].textContent);
  }
}

myFunction6()
<div class="row">
  <span class="red">66 
    <span>22 </span>
  </span>
  <span class="green">24
    <span class="blue" style="color: #000;">82 </span>
  </span>
  <span class="green">10 
    <span class="blue" style="color: #000;">1 </span>
  </span>
  <span class="red">69 
    <span>80 </span>
  </span>
  <span class="red">12 
    <span class="green" style="color: #000;">11 </span>
  </span>
</div>
    
answered by 14.05.2018 / 22:44
source
3

Can be done with css, try this code ... The span children are green.

$(document).ready(function(){
  $("span").each(function(){
    if($(this).parent().is("span")){
      $(this).hide();
    }
  });
});
div > span {
  color:red
  }
  span > span{
  color:green;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
    <span class="red">66 
        <span>22 </span>
    </span>
    <span class="green">24
        <span class="blue">82 </span>
    </span>
    <span class="green">10 
        <span class="blue" >1 </span>
    </span>
    <span class="red">69 
        <span>80 </span>
    </span>
    <span class="red">12 
        <span class="green">11 </span>
    </span>
 </div>
    
answered by 14.05.2018 в 22:32