Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide child elements using javascript

Tags:

javascript

<div id="wpq2">
   <div class="subClass">
   <a id="linkTO" class="subClass">New Item</a>
   or
   <a class="subClass">edit</a>
   this list
   </div>
</div>

i want to hide all the thing except

   <a id="linkTO" class="subClass">New Item</a>

I do not have access to html , i have to use javascript

i tried somthing

var parentID = document.getElementById('wpq2');
var sub = parentID.getElementsByClassName('subClass');
var lastChild = sub[0].lastChild;
lastChild.style.display = 'none';

Using javascript no idea how to do

Please suggest

like image 889
Prashobh Avatar asked Jul 20 '26 04:07

Prashobh


1 Answers

Try this instead:

var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get all the a elements
var subs = innerDiv.getElementsByClassName('subClass');

//This will hide all matching elements except the first one
for(var i = 1; i < subs.length; i++){
   var a = subs[i];
   a.style.display = 'none';
}

Here is a working example


EDIT: The above will only hide the a element, as your text elements are not contained within specific elements then it becomes more tricky. If you are happy to effectively "delete" the HTML you don't want then you can do the following:

var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get the HTML for the a element to keep
var a = innerDiv.getElementsByClassName('subClass')[0].outerHTML;
//replace the HTML contents of the inner DIV with the element to keep
innerDiv.innerHTML = a;

Here is an example

like image 119
musefan Avatar answered Jul 22 '26 18:07

musefan