How to set CSS class property in Javascript? - javascript

I'm trying change CSS class property value. I'm using this soluction:
let pizzas = document.querySelectorAll('.pizza');
pizzas.forEach( pizzaElement => pizzaElement.style.display = 'none' );
Anyone has a solution without use iteration?

It's better to use classList API with possibility to add, remove or toggle CSS classes: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

let pizzas = document.querySelectorAll('.pizza');
pizzas.forEach( pizzaElement => pizzaElement.classList.add('d-none') );
jsfiddle
EDIT:
Please describe exactly where you want to use it. If you do not want to change the property of any event it is unnecessary to do with JS. You can overwrite css or add a new class ..

if your using pure JavaScript You can use this code:
let pizzas = document.querySelectorAll('.pizza');
pizzas[0].style.display = 'none';
pizzas[1].style.display = 'none';
pizzas[2].style.display = 'none';
or if you are using JQuery you can use this:
$(document).ready(function(){
$('.pizza').css('display','none');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<DOCTYPE html>
<head>
</head>
<body>
<div class="pizza">Some Text</div>
<div class="pizza">Some Other Text</div>
<div class="pizza">Text</div>
</body>
</html>

Related

How to built a text array of the document content with javascript

Hi how can I extract the text of an document as an array within javascript.
It´s easy to get the innerHTML, but I do not get the text before and after the div for example.
This should be the output:
[0]=before div
[1]=innerHTML
[2]=aferHTML
[3]=before div2
[4]=innerHTML2
[5]=aferHTML2
Of the following document:
<html><head>
<body>
before div <div>innerHTML </div>aferHTML
before div2 <div>innerHTML2 </div>aferHTML2
</body></html>
I found this link, but it does not get the text before and after the elements as well:
How to get all text from all tags in one array?
You scenario is not clear. Could you please elaborate more the specific reason.
However if you want to get text from all elements in a document, kindly review this thread -> link.
By using the childNodes property you can achieve this. But for afterHtml and before div2, you need to do some extra work because they are part of the same text node.
Please take a look at the snippet below. You can remove the last element of the array manually.
const arr = [];
document.body.childNodes.forEach(node => {
arr.push(node.textContent.trim());
})
console.log(arr)
<body>
before div <div>innerHTML </div>aferHTML
before div2 <div>innerHTML2 </div>aferHTML2
</body>
Okay here's mine.
As you can see, I wrapped your HTML inside a div with a class name content.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="content">
before div <div>innerHTML </div>aferHTML
before div2 <div>innerHTML2 </div>aferHTML2
</div>
</body>
</html>
<script type="text/javascript">
var body = document.querySelector('.content').children;
var list = [];
for (var i = 0; i < body.length ; i++) {
var before = body[i].previousSibling.nodeValue.trim();
var inner = body[i].innerHTML;
var after = body[i].nextSibling.nodeValue.trim();
if (before && i == 0) list.push(before); //prevent duplication and empty value
list.push(inner);
if(after) list.push(after); //prevent empty value
}
console.log(list); //output
</script>
in innerHTML, you could split the string using inner.split(" ") if you like.

Javascript -> CSS (display:none to display:block)

I have 3 divs + 3 hidden divs. I want to click on "service1" and edit "display:block" in "toggle1".
The HTML:
<div id="service1" onclick="changeService('toggle1')></div>
<div id="service2"></div>
<div id="service3"></div>
<br><br>
<div id="toggle1"></div>
<div id="toggle2"></div>
<div id="toggle3"></div>
The CSS:
#toggle1, #toggle2, #toggle3 {display:none}
The Javascript:
function changeService(this) {
this.style.display = "block";
}
Hope I explained myself well enough so you guys can understand. What am I doing wrong?
Thanks in advance :)
You are passing a string into function, not an object. You can use document.getElementById method to get corresponding div element:
function changeService(id) {
document.getElementById(id).style.display = "block";
}
I think it would be best to use CSS classes.
So go:
#toggle1, #toggle2, #toggle3 {display:none}
#toggle1.active, #toggle2.active, #toggle3.active{display: block}
And then:
function changeService(id) {
document.getElementById(id).setAttribute("class", "active");
}
Then you can keep view and logic separated and easily add more style if necessary. Try never to change your CSS in Javascript. Better add classes like this to keep things clear.
https://jsfiddle.net/t74tmu7r/2/
first of all place your script file before the closing body tag to make sure all DOM elements are loaded then use this code:
function changeService(id){
var elem = document.getElementById(id);
elem.style.display = "block";
}
then in the div tag with a class name 'service1' do this:
<div id="service1" onClick="changeService('toggle1');"></div>
that should do the job.

lastChild not working

I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8"/>
<script type = "text/javascript" src = "js/jquery.js" ></script>
</head>
<body>
<div id = 'div'>
<div id = "1">
</div>
<div id = "2">
</div>
</div>
</body>
</html>
My JavaScript code is:
$(document).ready(function(){
var lastcommentq = document.getElementById('div').lastChild.id;
alert(lastcommentq);
});
It should alert the id of the lastchild of the div with the id 'div' which is '2' but I am getting the alert as "undefined". I don't know what I have done wrong. Please help me.
Your elements probably have text nodes around them, so the last child node of the outer <div> won't necessarily have an "id" attribute.
I'm not sure if all browsers support it, but there's a "lastElementChild" property that explicitly gets only elements, and not things like comment nodes or text nodes. Failing that, you could just loop through the node list looking for type 1 nodes.
is this your wanted behaivour?
$(document).ready(function(){
var lastchild = $("div").last().attr("id")
alert(lastchild);
});
<div id="div">
<div id ="1">
</div>
<div id="2">
</div>
</div>
check out this fiddle for live example
http://jsfiddle.net/sHgbF/
In jquery:
$(function(){
alert($("#div :last-child").attr('id'));
});
The jQuery way:
// assuming the last child is always a div
var lastcommentq = $('#div > div:last-child').attr('id');
// alternatively
var lastcommentq0 = $('#div').children('div').last().attr('id');
The JavaScript way:
var lastcommentq = document.getElementById('div').lastElementChild.id;
Note that this works in all modern browsers and IE 9+. See lastElementChild on MDN.
this is what I would have done, but I'm not clear as to if it's what you want:
$(function () {
var lastchild = $('#div div:last-child').attr('id');
alert(lastchild);
});
http://jsfiddle.net/pFjPS/
also, I don't believe classes or ids can start with numbers, so your markup is probably not valid
edit :
HTML5 supports it, but is not generally recommended.
I would use this approach, since ID is a property and not an attribute.
$(function () {
var lastchild = $('#div div:last-child').prop('id');
alert(lastchild);
});

Insert all divs with same class into an array?

I want to insert all divs which have the class .page into an array, then call each using the array iteration. For example the array pages[] should allow me to add certain effect to the div in pages[2].
var pageDivs = document.getElementsByClassName("page");
for(i = 0; i < pageDivs.length;i++)
{
//apply your effects using pageDivs[i]
}
Do you want to do like this ?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr=[];
$(".page").each(function(){ arr.push($(this));});
$.each(arr,function(key,val){ val.css('color','gray')});
});
</script>
</head>
<body>
<b>.page content will be colored in gray.</b><br/><br/>
<div class="dontDo">The quick </div>
<div class="page">brown fox jumps</div>
<div class="doIt"> over the lazy dog</div>
<div class="page"> over the lazy dog</div>
</body>
</html>
I think in some of browsers getElementByClassName is not supported.However you can use calssName property like this :
function getElementsByClassName( strClassName, obj ) {
if ( obj.className == strClassName ) {
//insert this elm into array
array.push(obj);
}
}
.getElementsByClassName is not supported < IE8. If you aren't worried about that, then Sunil's response will work for you.
If you want the jQuery way:
$(".page").each(function(index) {
// do stuff here
});
Happy iterating.

jquery get styles from an id

does anyone know how can i get all styles applied to an id using jquery (so i can reuse it later in another tag)? something like
css:
div#myid{
width:100px;
height:100px;}
so i can later do something like:
for (var parts in $('#myid').css())
alert ('all parts of the style' + parts);
$('#myid').attr('class') returns a string of the classes.
You should be able to figure it out from here.
var classes = $('#myid').attr('class').split(' ');
for(var c in classes)
{
alert(classes[c]);
}
It is not jquery but works well:
var style = window.getComputedStyle(document.getElementById('myid'), null);
alert(style.color);
You can replace document.getElementById('myid') by $('#myid').get(0) if you really want to use jquery here.
This works either for a style given by CSS or directly applied on the element with the style attribute.
Not sure.. I had tried attr('class') before and it returned empty. trying now again produces the same result (nearly). i suppose attr('class') in jquery isnt exactly the same as styles defined via id. try running this, let me know if you get different results please:
<html>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
alert($('#myid').attr('class')); // returns 'empty'
var classes = $('#myid').attr('class').split(' ');
for(var c in classes){
alert(c); // returns 0
}
});
</script>
<style>
#myid {
width:100px;
height:100px;
background:red;
}
</style>
<body>
<div id="myid"></div>
</body>
</html>

Categories