Hello i want to remove "Have you served in the military ?" and "No" if Answer is "No" but when it will "Yes" than it should show.
Whatever i have tried but it's not working
<script type="text/javascript">
(function(){
for(i = 0; (a = document.getElementsByTagName("td")[i]); i++){
if(document.getElementsByTagName("span")[i].innerHTML.indexOf('Have you served in the military') > -1){
document.getElementsByTagName("td")[i].style.display = "none";
}
}
})();
</script>
You could use child of the element or just do a find replace or even hide and show.
You can get all td elements like you already did and than get the span elements inside them:
var tds = document.getElementsByTagName('TD');
for (var i = 0, l = tds.length; i != l; ++i) {
var spans = tds[i].getElementsByTagName('SPAN');
for (var j = 0, l2 = spans.length; j != l2; ++j) {
var span = spans[j];
if ((span.textContent = span.innerText).indexOf('Have you served in the military') != -1) {
span.style.display = 'none';
break;
}
}
}
EDIT: OP wants to only delete the span if there is a td with the content "No" (also delete the td element)
var tds = document.getElementsByTagName('TD');
var tdsLength = tds.length;
var answerNoFound = false;
for (var i = 0; i != tdsLength; ++i) {
var td = tds[i];
if ((td.textContent = td.innerText) == 'No') {
td.style.display = 'none';
answerNoFound = true;
break;
}
}
if (answerNoFound)
for (var i = 0; i != tdsLength; ++i) {
var spanFound = false;
var spans = tds[i].getElementsByTagName('SPAN');
for (var j = 0, l = spans.length; j != l; ++j) {
var span = spans[j];
if ((span.textContent = span.innerText).indexOf('Have you served in the military') != -1) {
span.style.display = 'none';
spanFound = true;
break;
}
}
if (spanFound)
break;
}
It looks like you have an application form and document probably has more spans, some outside the td elements, so you don't get correct selection of spans versus td.
So when you are comparing span content, it is most likely not the span that is inside your looped td.
<script type="text/javascript">
(function(){
for(i = 0; (a = document.getElementsByTagName("td")[i]); i++){
if(a.getElementsByTagName("span")[0].innerHTML.indexOf('Have you served in the military') > -1){
a.style.display = "none";
}
}
})();
</script>
I changed the if statement to select span inside your looped td, that should do it.
Related
I have this code, repeating 20 times with only change of variables prefix. How can i possibly make a loop and iterate by it to avoid this huge block of code?
It is used in my website and I want to make the development process more clear.
var keepElements = document.getElementsByName("keep-type");
for(var i = 0; i < keepElements.length; i++){
keep = document.getElementById(keepElements[i].value);
if(keepElements[i].checked == true){
keep.style.display = "block";
}
else{keep.style.display = "none";}
}
var offworkshopElements = document.getElementsByName("offworkshop-type");
for(var i = 0; i < offworkshopElements.length; i++){
offworkshop = document.getElementById(offworkshopElements[i].value);
if(offworkshopElements[i].checked == true){
offworkshop.style.display = "block";
}
else{offworkshop.style.display = "none";}
}
var defworkshopElements = document.getElementsByName("defworkshop-type");
for(var i = 0; i < defworkshopElements.length; i++){
defworkshop = document.getElementById(defworkshopElements[i].value);
if(defworkshopElements[i].checked == true){
defworkshop.style.display = "block";
}
else{defworkshop.style.display = "none";}
}
Move the logic to a function:
function keepElements(name) {
var keepElements = document.getElementsByName(name);
for (var i = 0; i < keepElements.length; i++) {
keep = document.getElementById(keepElements[i].value);
if (keepElements[i].checked == true) {
keep.style.display = "block";
}
else { keep.style.display = "none"; }
}
}
keepElements("keep-type");
keepElements("offworkshop-type");
keepElements("defworkshop-type");
If I didn't miss any details, you're repeating the same block 3 times:
["keep-type", "offworkshop-type", "defworkshop-type"].forEach(name => {
var elements = document.getElementsByName(name);
for(var i = 0; i < elements.length; i++){
element = document.getElementById(elements[i].value);
if(elements[i].checked == true){
element.style.display = "block";
}
else{element.style.display = "none";}
}
});
I prefer the array / forEach syntax, because the block starts with the list of name. But you could use a for...of loop instead.
for (const name of ["keep-type", "offworkshop-type", "defworkshop-type"]) {
var elements = document.getElementsByName(name);
for(var i = 0; i < elements.length; i++){
element = document.getElementById(elements[i].value);
if(elements[i].checked == true){
element.style.display = "block";
}
else{element.style.display = "none";}
}
}
The answers saying you should put the common functionality into a single function are absolutely right.
I just wanted to add that there are also solutions on the query side of things:
you could have all the elements be collected in one javascript function, querySelectorAll()
const elements = document.querySelectorAll('[name="keep-type"], [name="offworkshop-type"], [name="defworkshop-type"]')
Alternatively you could give them all the same class and select by that class.
const elements = document.getElementsByClassName("requiredElements");
And this way you have all your elements in one array.
I am trying to write a javascript for hidding all elements of the class "prewrap", when any image on
the webpage is clicked.
Code so far:
<script type="text/javascript">
function hidepre() {
var elems = document.getElementsByClassName("prewrap");
for (var i = 0; i < elems.length; i++) {
if (elems[i].style.visibility === "hidden") {
elems[i].style.visibility = "visible";
} else {
elems[i].style.visibility = "hidden";
}
}
}
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = "hidepre()";
}
</script>
Jsfiddle: http://jsfiddle.net/aX5kQ/
But this is not working at all, any idea what went wrong?
Your code is working, check this fiddle DEMO
EDIT
Remove the script tag from your jsfiddle leave only the code.
function hidepre() {
var elems = document.getElementsByClassName("prewrap");
for (var i = 0; i < elems.length; i++) {
if (elems[i].style.display === "none") {
elems[i].style.display = "block";
} else {
elems[i].style.display = "none";
}
}
}
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = hidepre;
}
Also in your post this line should be corrected ->
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = hidepre; //this line - here should only be the name of the function without quotes and parentheses
}
It works just fine if you remove the script tag from the JS area of jsfiddle (you put raw javascript in there.. no tags)
edited demo at http://jsfiddle.net/aX5kQ/1/
Hi this code is executed immediately before the image is loaded and so no img is found.
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
imgs[i].onclick = "hidepre()";
}
Execute this when the DOM is finished loading with window.onload = ...
I only want to remove images from a content div, not the whole site. I have tried the following:
var elements = document.getElementsByTagName('img');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
That removes every image.
var elements = document.getElementsById('content').document.getElementsByTagName('img');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
That did nothing.
Can someone tell me what I am doing wrong?
var elements = document.getElementsById('content').document.getElementsByTagName('img');
should be
var elements = document.getElementsById('content').getElementsByTagName('img');
var elements = document.getElementsById('content').getElementsByTagName('img');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
if using jQuery
$('#content img').hide();
I am trying to hide a row which contains in one of the cells a specific span element. The following code is what I have so far - but there is no getElementsByTagName for a tr
What else can I do to get the row? Thanks !
<table id='tableContainer'>
<tr><td><span id='xyz'>Hide</span></td></tr>
<tr><td><span id='abc'>Show</span></td></tr>
</table>
container = document.getElementById('tableContainer');
items = container.getElementsByTagName('tr');
for (var j = 0; j < items.length; j++) {
spans = items.getElementsByTagName('span');
for (var i=0; i<spans.length; i++) {
if (spans.id == 'xyz') {
items.display = 'none';
}
}
}
spans and items are arrays of nodes, so you forgot to get each one by array index, it should be like this,
<table id='tableContainer'>
<tr><td><span id='xyz'>Hide</span></td></tr>
<tr><td><span id='abc'>Show</span></td></tr>
</table>
container = document.getElementById('tableContainer');
items = container.getElementsByTagName('tr');
for (var j = 0; j < items.length; j++) {
spans = items[j].getElementsByTagName('span');
for (var i=0; i<spans.length; i++) {
if (spans[i].id == 'xyz') {
items[j].style.display = 'none';
}
}
}
DEMO
UPDATE:
And don't forget to put style before display.
items[j].display = 'none'; // false
items[j].style.display = 'none'; // true
So let us debug a little:
container = document.getElementById('tableContainer');
console.log(container) //<-- Gives you tag element
items = container.getElementsByTagName('tr');
console.log(items); //<-- Gives you HTML Collection
for (var j = 0; j < items.length; j++) {
spans = items.getElementsByTagName('span'); //<-- error says items.getElementsByTagName is not a function
for (var i=0; i<spans.length; i++) {
if (spans.id == 'xyz') { //<--error here [not referencing index]
items.display = 'none'; //<--error here [not setting style and index]
}
}
}
Problem here is you are not indexing each tr, you are trying to run it on the whole html collection.
spans = items.getElementsByTagName('span');
should be
spans = items[j].getElementsByTagName('span');
You need to do the same thing in the spans loop so the final code would be
container = document.getElementById('tableContainer');
console.log(container) //<-- Gives you tag element
items = container.getElementsByTagName('tr');
console.log(items); //<-- Gives you HTML Collection
for (var j = 0; j < items.length; j++) {
spans = items[j].getElementsByTagName('span'); //<-- use index
items.getElementsByTagName is not a function
for (var i=0; i<spans.length; i++) {
console.log(spans[i].id)
if (spans[i].id == 'xyz') { //<-- use index
items[j].style.display = 'none'; //<-- use index and display
}
}
}
Running example: JSFiddle
How can I toggle multiple rows in a table if the <td> class is set to an specific class. For instance toggle all rows if they contain the class="foo".
<table id="bar">
<tr>
<td>hello</td>
<td class="foo">there</td>
<td class="foo">bye</td>
</tr>
</table>
Here's a non-jQuery solution, written just for you: http://phrogz.net/tmp/toggling_rows_with_class.html
Here's the relevant JS:
window.onload = function() {
var visible = true;
document.getElementById('toggle').onclick = function() {
visible = !visible;
var tds = findElementsWithClass('td', 'foo');
for (var i=0, len=tds.length; i<len; ++i) {
tds[i].parentNode.style.display = visible ? '' : 'none';
}
};
}
function findElementsWithClass(tagName, className) {
if (document.querySelectorAll) {
return document.querySelectorAll(tagName + "." + className);
} else {
var results = [];
var all = document.getElementsByTagName(tagName);
var regex = new Regexp("(?:^|\\s)" + tagName + "(?:\\s|$)");
for (var i=0, len=all.length; i<len; ++i) {
if (regex.test(all[i].className)) {
results.push(all[i]);
}
}
return results;
}
}
Modify the class
Why is everyone using selectors? There is already a class attached to all the appropriate elements, so why not just modify the class?
This function will find the class of a given name, and set an attribute for that class. Be careful if you have multiple classes with coincident names in different stylesheets, because the function isn't!
function changeStyle(stylename,attribute,newvalue) {
var cssRules = 'rules';
if(document.styleSheets[0].cssRules) {
cssRules = 'cssRules';
}
for(var sheetId=0; sheetId<document.styleSheets.length; sheetId++) {
var sheet = document.styleSheets[sheetId];
for(var ruleId=0; ruleId<sheet[cssRules].length; ruleId++) {
var rule = sheet[cssRules][ruleId];
if(rule.selectorText == "."+stylename) {
rule.style.setProperty(attribute,newvalue,"");
}
}
}
return false;
}
Now, just call
changeStyle('foo','display','none');
and the cells should disappear, then with 'block' to get them back (IE can't do the more recent display styles like ). I suspect that in a table you'll want to hide entire rows rather than just cells, but you can also make them disappear by setting visibility to hidden - they will still take up space, but not draw.
See, no jquery, no homemade element selectors. Just a slightly annoying bit of javascript to loop through the stylesheets and their rules...
td = document.getElementsByTagName('td');
for (var i = 0; i < td.length; i++) {
if (td[i].className === 'foo')
if (!td[i].style.display)
td[i].style.display = 'none';
else
td[i].style.display = '';
}
}
http://jsfiddle.net/qwertymk/cyZn9/2/
Something like this should do it:
var trs = document.getElementsByTagName("tr");
for (var i in trs) {
var tr = trs[i];
if (tr.getElementsByClassName("foo").length > 0)
tr.style.display = (tr.style.display == "none" ? "block" : "none");
}
This will toggle the display on any TR that contains a child with class="foo".
Something like this?
$("table td.specific_class").toggle();
Edit
/* Go through the table rows */
var trs = document.getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++ ) {
var myClass, tds, line_done = false;
/* Go through the table cells */
tds = trs[i].getElementsByTagName("td");
for ( var k = 0; k < tds.length; k++ ){
/* Check each class of each cell */
myClasses = tds[k].className.split(' ');
for ( var j = 0; j < myClasses.length; j++ ){
/* If the class corresponds we toggle the row and break until the next row */
if ( myClasses[j].className == "foo" ){
trs[i].style.display = trs[i].style.display == "none" ? "block" : "none";
line_done = 1;
break;
}
}
if ( line_done ){
break;
}
}
}
try this one
<html>
<head>
<title>test</title>
<script type="text/javascript">
var toggle = function (action) {
var trs = document.getElementById('bar').getElementsByTagName('tr'),
trs_count = trs.length,
needed = [],
total = 0,
pattern = /\bfoo\b/g,
initial= 'show';
for (i=0; i<trs_count; i++) {
var tds = trs[i].getElementsByTagName('td'),
tds_count = tds.length;
for (j=0; j<tds_count; j++) {
if (pattern.exec(tds[j].className)) {
needed.push(tds[j]);
total++;
}
}
}
toggle = function (action) {
if (this.display == null) {
this.display = initial;
}
if (action == null) {
this.display = (this.display == 'hide') ? 'show' : 'hide';
}
else {
this.display = action;
}
for (i=0; i<total; i++) {
if (this.display == 'show') {
needed[i].style.display = 'block';
}
else {
needed[i].style.display = 'none';
}
}
return true;
}
return toggle();
}
</script>
</head>
<body>
<table id="bar">
<tr><th>Header</th></tr>
<tr><td class="foo">1 Data foo</td></tr>
<tr><td>2 Data</td></tr>
<tr><td class="foo">3 Data foo</td></tr>
<tr><td>4 Data</td></tr>
</table>
<button type="button" onclick="toggle()">toggle</button>
</body>
</html>