I'm trying create a loop (or use .each
) to change the style:display
property of many DOM elements. My initial thought was to use getElementsByName
to select all of the elements that I named ptext1
:
<p id="ptext0"name="ptext">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p id="ptext1"name="ptext1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p id="ptext2"name="ptext1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p id="ptext3"name="ptext1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p id="ptext4"name="ptext1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p id="ptext5"name="ptext1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p id="ptext6"name="ptext1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
using
var TextElements = document.getElementsByName("ptext1");
To make an object/array of all of the elements with the name ptext1
But I could not get that method working correctly so I moved onto the .each
.
Both
$.each(TextElements, function (index) {
this.style.display="none";
});
and
$('td[name=ptext1]').each(function (index) {
this.style.display="block";
});
Didn't seem to work properly (I've been testing whether it runs using alerts).
Now if anyone can see where my mistake is or suggest a better method I am all ears. This SHOULD be a simple operation but for some reason each time I try, it fails.
Edit:
$('p[name=ptext1]').hide()
and $('p[name=ptext1]').show()
are working except .hide() also hides the line above the ones I would like to hide,
<p id="ptext0"name="ptext">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
Each line has a different id tag, but I am trying to use the name tag to keep track of which ones I would like to hide, yet the line that should remain (name="ptext") also hides.
Why don't you simply use:
$('p[name="ptext1"]').css( 'display', 'none');// you can use block...
If you want to keep a line shown, exclude that line with .not()
:
$('p[name="ptext1"]').not('#ptext3').css( 'display', 'none');// you can use block...
http://jsfiddle.net/4JCvt/
And if you just want to use vanilla JavaScript, you can do:
var TextElements = document.getElementsByName("ptext1");
for (var i = 0, max = TextElements.length; i < max; i++) {
TextElements[i].style.display = "none";
}
http://jsfiddle.net/4JCvt/2/
Use this with JQuery:
$("[name='ptext1']").css("display", "value");
//change value to the display value you want
//$("[name='ptext1']").css("display", "block");
Pure JavaScript:
var elements = document.getElementsByName("ptext1");
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "value";
}
//also change value to display value wanted.
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