On my web page I want to 'hide' or 'unhide' several elements (C and F in this example) that are already inside a DIV element,
such as:
<div> Select A or B <span name='hide' > or C</span></div>
<div> Also select D or E <span name='hide' > or F</span></div>
(etc)
I use javascript to hide all 'hide' elements when the page is opened, except when the page is opened on localhost, than all is shown.
I do not necessarily know how many 'hide' elements there are (dynamically generated).
var hids=document.getElementsByName('hide');
if(hids!=null) {
for(var j=0; j< hids.length; j++) {
if(localhost==true) { // only if on localhost
hids[j].style.visibility='visible';
}
else hids[j].style.visibility='hidden';
}
}
But, the 'name' attribute is not valid for SPAN. When I use DIV instead of SPAN it messes up the format. How should I solve this properly?
Use class instead of name:
<span class="my-class"> or C</span>
and getElementsByClassName instead of getElementsByName:
document.getElementsByClassName("my-class");
If span doesn't have a name attribute, try with class name
var hids=document.getElementsByClassName('hide');
And change your html to
<div> Select A or B <span class='hide' > or C</span></div>
<div> Also select D or E <span class='hide' > or F</span></div>
You can use querySelectorAll to find by className hide
var localhost = false;
var hids = document.querySelectorAll('.hide');
if (hids != null) {
for (var j = 0; j < hids.length; j++) {
if (localhost) { // only if on localhost
hids[j].style.visibility = 'visible';
} else hids[j].style.visibility = 'hidden';
}
}
<div> Select A or B <span class='hide'> or C</span></div>
<div> Also select D or E <span class='hide'> or F</span></div>
(etc)
Resource
document.querySelectorAll()
Use data-XXX attribute instead of name, e.g.: <span data-name='hide'>
For sure, in this case, you will need to fetch them like this:
document.getElementsByTagName("data-name") and do another filtering based on the value of the data-name tag.
Im not sure the name property should be used here. I believe names are intended to be unique. So instead maybe through class name;
let localhost = true;
let hideList = document.getElementsByClassName("hide");
if (hideList != null) {
for (var j=0; j < hideList.length; j++ ) {
if (localhost === true) {
hideList[j].style.visibility = 'visible'
} else {
hideList[j].style.visibility = 'hidden'
}
}
}
As for the <div> messing up your formatting; thats likely due to a style property: display. <span>'s behave like display: inline; while <div>'s behave like display: block;. You can override this default behavior in your own CSS. Go ahead and turn those <spans>'s into <div>'s and apply some CSS:
<div> Select A or B <div class="hide"> or C</div></div>
<div> Also select D or E <div class="hide"> or F</div></div>
<style>
.hide {
display: inline;
}
</style>
The result should be visually identical to when using spans.
Related
I am writing a chrome extension where I working on a webpage which lists some things. So, basically, I am reading that table and doing some calculation in the javascript and showing them. Now, there is a filter option on the webpage. After filtering, it doesn't show some things on the list according to the filter selected. And it does so, by making the display as none. It makes the display as none by doing something like below:
[data-assignee]:not([data-aggr-assignees*="|xyz|"]) {
display: none;
}
So, when I am trying to find the elements whose display is not none to see the filtered items, it is giving all items since looks like it is not changing the CSS property of the items. I checked the style.display values of all the elements and it is coming '' for all. Can someone help me in how can I get the elements whose display is block in this kind of case?
You can query selector the whole document with * and go through each element with a for loop to check if its inline display property is set to none. Of course, this will only handle cases when the element is hidden with inline CSS.
<div style="display: block;">
DIV
</div>
<span style="display: none;"></span>
<script>
var allElems = document.querySelectorAll("*");
var visibleElems = [];
var hiddenElems = [];
for(let i = 0; i < allElems.length; i++){
if(allElems[i].style.display != "none"){
visibleElems.push(allElems[i]);
} else {
hiddenElems.push(allElems[i]);
}
}
console.log("Visible elements: "+visibleElems);
console.log("Hidden elements: "+hiddenElems);
</script>
If you want to check the display property of the elements from the CSS stylesheet, you will need to use window.getComputedStyle.
.hidden{
display: none;
}
<div style="display: block;">
DIV
</div>
<textarea class="hidden"></textarea>
<span style="display: none;"></span>
<style>
</style>
<div class="hidden">
</div>
<select class="hidden"></select>
<script>
var allElems = document.querySelectorAll("*");
var visibleElems = [];
var hiddenElems = [];
for(let i = 0; i < allElems.length; i++){
if(allElems[i].style.display == "none"||window.getComputedStyle(allElems[i], null).getPropertyValue("display")=="none"){
hiddenElems.push(allElems[i]);
} else {
visibleElems.push(allElems[i]);
}
}
console.log("Visible elements: "+visibleElems);
console.log("Hidden elements: "+hiddenElems);
</script>
I am trying to select one ore more elements that are NOT descendants of another specific element.
<html>
<body>
<div>
<p>
<b>
<i> don't select me </i>
</b>
</p>
</div>
<div>
<i>don't select me either </i>
</div>
<i> select me </i>
<b>
<i> select me too </i>
</b>
</body>
</html>
In the example above I want to select all 'i' elements, that are not inside div elements.
The other way around would be easy, with ('div i'), but using this in :not() is not possible.
How can I select all i elements outside of div elements?
Often it is suggested the use of jQuery, which would be like:
nondiv_i = all_i.not(all_div.find("i"))
I can't use jQuery, but could use jqLite - jqLite does not have a not()-function. A jqLite solution is welcome too!
Is it possible to do this without repeated iterations and comparisons?
Edit: To clarify, i don't want to have any div-ancestors for my i-elements, not only no direct div-parents.
A comparable XPath would look like this:
//i[not(ancestor::div)]
function isDescendant(parent, child) {
var all = parent.getElementsByTagName(child.tagName);
for (var i = -1, l = all.length; ++i < l;) {
if(all[i]==child){
return true;
}
}
return false;
}
for the specific case of yours;
is = document.getElementsByTagName("i");
divs = document.getElementsByTagName("div");
nondivs = [];
var contains;
for(i=0;i<is.length;i++){
contains = false;
for(j=0;j<divs.length;j++){
if(isDescendant(divs[j],is[i])){
contains = true;
j = divs.length;
}
}
if(!contains){
nondivs.push(is[i]);
}
}
Add a class to all of the <i> tags ("itag", for example). From there, you can fetch them by calling getElementsByClassName:
var r = document.getElementsByClassName("itag");
console.log("length" + r.length);
You can then get them by index:
console.log(r[0]);
console.log(r[1].innerHTML); // get text of i tag
I'm trying to only show certain divs. The way I have decided to do this is to first hide all elements that start with "page" and then only show the correct divs. Here's my (simplified) code:
<form>
<input type="text" onfocus="showfields(1);">
<input type="text" onfocus="showfields(2);">
</form>
<div class="page1 row">Some content</div>
<div class="page1 row">Some content</div>
<div class="page2 row">Some content</div>
<div class="page2 row">Some content</div>
<script>
function showfields(page){
//hide all items that have a class starting with page*
var patt1 = /^page/;
var items = document.getElementsByClassName(patt1);
console.log(items);
for(var i = 0; i < items.length; i++){
items[i].style.display = "none";
}
//now show all items that have class 'page'+page
var item = document.getElementsByClassName('page' + page);
item.style.display = '';
}
</script>
When I console.log(items); I get a blank array. I'm pretty sure the regexp is right (get all items starting with 'page').
The code I'm using is old school JS, but I'm not adverse to using jQuery. Also if there is a solution that doesn't use regexp, that's fine too as I'm new to using regexp's.
getElementsByClassName only matches on classes, not bits of classes. You can't pass a regular expression to it (well, you can, but it will be type converted to a string, which is unhelpful).
The best approach is to use multiple classes…
<div class="page page1">
i.e. This div is a page, it is also a page1.
Then you can simply document.getElementsByClassName('page').
Failing that, you can look to querySelector and a substring matching attribute selector:
document.querySelectorAll("[class^=page]")
… but that will only work if pageSomething is the first listed class name in the class attribute.
document.querySelectorAll("[class*=page]")
… but that will match class attributes which mention "page" and not just those with classes which start with "page" (i.e. it will match class="not-page".
That said, you could use the last approach and then loop over .classList to confirm if the element should match.
var potentials = document.querySelectorAll("[class*=page]");
console.log(potentials.length);
elementLoop:
for (var i = 0; i < potentials.length; i++) {
var potential = potentials[i];
console.log(potential);
classLoop:
for (var j = 0; j < potential.classList.length; j++) {
if (potential.classList[j].match(/^page/)) {
console.log("yes");
potential.style.background = "green";
continue elementLoop;
}
}
console.log("no");
potential.style.background = "red";
}
<div class="page">Yes</div>
<div class="notpage">No</div>
<div class="some page">Yes</div>
<div class="pageXXX">Yes</div>
<div class="page1">Yes</div>
<div class="some">Unmatched entirely</div>
Previous answers contain parts of the correct one, but none really gives it.
To do this, you need to combine two selectors in a single query, using the comma , separator.
The first part would be [class^="page"], which will find all the elements whose class attribute begins with page, this selector is thus not viable for elements with multiple classes, but this can be fixed by [class*=" page"] which will find all the elements whose class attribute have somewhere the string " page" (note the space at the beginning).
By combining both selectors, we have our classStartsWith selector:
document.querySelectorAll('[class^="page"],[class*=" page"]')
.forEach(el => el.style.backgroundColor = "green");
<div class="page">Yes</div>
<div class="notpage">No</div>
<div class="some page">Yes</div>
<div class="pageXXX">Yes</div>
<div class="page1">Yes</div>
<div class="some">Unmatched entirely</div>
You can use jQuery solution..
var $divs = $('div[class^="page"]');
This will get all the divs which start with classname page
$(document).ready(function () {
$("[class^=page]").show();
$("[class^=page]").hide();
});
Use this to show hide div's with specific css class it will show/hide all div's with css class mention.
In css I have set all the <hr> elements in my html to "display:none;" which works.
I have an onclick event listener set up to change the "display" to "block".
I use:
document.getElementsByTagName("hr").innerHTML.style.display = "block";
I get an error "Cannot read property 'style' of undefined".
Do it the following way:
var hrItems = document.getElementsByTagName("hr");
for(var i = 0; i < hrItems.length; i++) {
hrItems[i].style.display = 'block';
}
This is incorrect in two ways
getElementsByTagName gives you a list on elements and there is no method to operate on all elements, so you'll have to loop through all of them and add the required style individually.
innerHTML returns a string containing the mark up in an element but <hr> doesn't have any thing in it and the style property is on the <hr> itself.
var hrs = document.getElementsByTagName("hr");
for(var i = 0; i < hrs.length; i++) {
hrs[i].style.display = 'block';
}
Simple (and very effective) solution:
tag your body with a class-element
<body class="no_hr"> <article><hr/> TEXT Foo</article> <hr/> </body>
in css don't hide hr directly, but do
.no_hr hr {
display:none;
}
now define a second style in your css
.block_hr hr{
display:block;
}
in your buttons onClick, change the one and only body class from no_hr to block_hr
onclick() {
if ( document.body.className == "no_hr" ) {
document.body.className = "block_hr";
} else {
document.body.className = "no_hr";
}
}
This is a very charming solution, because you don't have to iterate over elements yourself, but let your browsers optimized procedures do their job.
For people who want a solution that doesn't require JavaScript.
Create an invisible checkbox at the top of the document and make sure that people can click on it.
<input type="checkbox" id="ruler"/>
<label for="ruler">Click to show or hide the rules</label>
Then tell the stylesheet that the <hr>s should be hidden by default, but should be visible if the checkbox is checked.
#ruler, hr {display:none}
#ruler:checked ~ hr {display:block}
Done. See fiddle.
getElementsByTagName() returns a node list, and therefore you must iterate through all the results. Additionally, there is no innerHTML property of an <hr> tag, and the style must be set directly on the tag.
I like writing these types of iterations using Array.forEach() and call:
[].forEach.call(document.getElementsByTagName("hr"), function(item) {
item.style.display = "block";
});
Or, make it even easier on yourself and use jQuery:
$("hr").show();
This question already has answers here:
javascript variable corresponds to DOM element with the same ID [duplicate]
(3 answers)
Closed 9 years ago.
I have multiple spans
<span id ="myId">data1</span>
<span id ="myId">data2</span>
<span id ="myId">data3</span>
<span id ="myId">data4</span>
<span id ="myId">data5</span>
I want to delete text inside all span on single button click.
I tried this on button click in javascript
document.getElementById("myId").innerHTML = "";
but it is removing text from only 1st span
IDs are unique, Classes are repeatable
The purpose of an id in HTML is to identify a unique element on the page. If you want to apply similar styles or use similar scripts on multiple elements, use a class instead:
<span class="myClass">data1</span>
<span class="myClass">data2</span>
<span class="myClass">data3</span>
<span class="myClass">data4</span>
<span class="myClass">data5</span>
<input type="button" id="clearbutton" value="Clear Data">
Now let's remove the text
Now, you can select all of these elements and set their text to anything you want. This example uses jQuery, which I recommend because older versions of IE don't support getElementsByClassName:
$('#clearbutton').click(function() {
$('.myClass').text('');
});
Link to Working Demo | Link to jQuery
Or in Vanilla JS
If you're not worried about supporting IE, you can do this with vanilla JavaScript:
function clearSpans() {
var spans = document.getElementsByClassName("myClass");
for(var i=0; i < spans.length; i++) ele[i].innerHTML='';
}
Link to Working Demo
Note: You can add getElementsByClassName to IE
I wouldn't recommend doing this because it's simpler and more widely accepted to just use jQuery, but there have been attempts to support older IEs for this function:
onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
Link to source
Dont give same ID to more than one one tag, use class instead
<span class ="myId">data1</span>
<span class ="myId">data2</span>
<span class ="myId">data3</span>
<span class ="myId">data4</span>
<span class ="myId">data5</span>
call this function to clear
function clearAll()
{
var ele= document.getElementsByClassName("myId");
for(var i=0;i<ele.length;i++)
{
ele[i].innerHTML='';
}
}
You are using a DOM method that relies to the DOM of ID, that is, per DOM, there can only be one element with the same ID.
However, you do not use the id attribute that way in your HTML, so instead you are looking for the selector to query all elements with the id myId, you perhaps know it from CSS:
document.querySelectorAll("#myId").innerHTML = '';
This does not work out of the box, you also need to add the innerHTML setter to the NodeList prototype, but that is easy:
Object.defineProperty(NodeList.prototype, "innerHTML", {
set: function (html) {
for (var i = 0; i < this.length; ++i) {
this[i].innerHTML = html;
}
}
});
You find the online demo here: http://jsfiddle.net/Pj4HD/
var spans=document.getElementsByTagName("span");
for(var i=0;i<spans.length;i++){
if(spans[i].id=="myId"){
spans[i].innerHTML="";
}
}
Although I suggest you don't keep same IDs
http://jsfiddle.net/YysRp/