I need to hide all elements of type 'section' in my document apart from one with a particular ID.
In jquery this would be easy
$("section").hide();
$("section#myId").show();
How would I do this without jquery??
(I need it to happen as soon as the page loads and to not be noticable). I also need it to work cross browser.
Thanks.
To get all of the attributes of a DOM element: Use the getAttributeNames() method to get an array of the element's attribute names. Use the reduce() method to iterate over the array. On each iteration, add a new key/value pair containing the name and value of the attribute.
Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.
The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection.
DOMElement.getElementsByTagName
is your friend:
var sections = document.getElementsByTagName('section');
var mySection = null;
for(var i = 0; i < sections.length; ++i) {
if(sections[i].id === "myId") {
mySection = sections[i];
mySection.style.display = "block";
break;
}
sections[i].style.display = "none";
}
Place the following immediately before the </body> in your HTML
<script>
(function () {
for(var els = document.getElementsByTagName ('section'), i = els.length; i--;)
els[i].id !== "myId" && (els[i].style.display = "none");
}) ();
</script>
or in "modern" (HTML5) browsers :
<script>
[].forEach.call (document.querySelectorAll ('section'),
function (el) { el.id !== "myId" && (el.style.display = "none"); })
</script>
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