I've been poking around in similar questions but nothing has quite matched what I'm trying to do.
Basically, I'm working on a simple chrome extension for fun / to teach myself how scripts interact with chrome. I got a simple script working that will show/hide a given div:
function showHide() {
var e = document.getElementsByClassName("Line");
for ( var i=0, len=e.length; i<len; ++i ){
if(e[i].style.display == 'block')
e[i].style.display = 'none';
else
e[i].style.display = 'block';
}
}
As you'd expect, this hides every instance of "Line" on the page. The next step is to try to hide only divs that contain a certain string. I've been playing around with 'innerHTML.indexOf("Line")' but so far nothing has worked. Most often I'm getting this error: Uncaught TypeError: Cannot read property 'indexOf' of undefined
Intuitively, I'm trying to make something along the lines of:
if (e.innerHTML.indexOf("foo") != -1) { showHide(e); }
But I'm not sure how to integrate that conditional with the showHide() function I have working. I think I'm handling the 'if' statements sloppily, but since I'm pretty rusty with javascript, I'm mostly working by trial and error.
Just posting here in hope I can get some tips/direction.
You can try iterating through the child nodes and checking their Inner Html. Check out the snippet.
Cheers!
var showHide = function(e) {
e.style.display = (e.style.display === 'block') ? 'none' : 'block'
}
function toggle() {
doStuff();
}
function eContainsNodeValue(element, foo){
var childs = element.childNodes;
for (j = 0; j<childs.length; j++){
if (childs[j].innerHTML === foo)
return true;
}
return false;
}
function doStuff() {
var elements = document.getElementsByClassName("Line");
for (i = 0; i< elements.length; i++){
if (eContainsNodeValue(elements[i], 'foo'))
showHide(elements[i]);
}
}
#MyDiv {
background-color: #6699ff;
}
.Line {
display: block;
background-color: #000000;
color: #6699ff;
width: 100%;
text-align: center;
}
<body id="MyDiv">
<div class="Line" style="display: block">
<h4>I'm a line 1!</h4>
</div>
<div class="Line" style="display: block">
<h4>I'm a line 2!</h4>
</div>
<div class="Line" style="display: block">
<h4>I'm a line 3!</h4>
</div>
<div class="Line" style="display: block">
<h4>I'm a line 4!</h4>
<p>foo</p>
</div>
<div class="Line" style="display: block">
<h4>I'm a line 5!</h4>
<p>bar</p>
</div>
<div class="Line" style="display: block">
<h4>I'm a line 6!</h4>
</div>
<button onclick="toggle()">Toggle foo bar</button>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With