how i can create a javascript code to add class name to specific divs only
for Exapmle : i want to add a class_name to from div5 to the end of all divs ?
try this
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
</script>
</body>
</html>
If you're looking to add a class name from one div to others, I would recommend using JQuery. This can be done like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function changeColor(){
$( document ).ready(function() {
$("div").addClass("work");
});
}
</script>
<style>
.work {
color: red
}
</style>
<div style="width: 100%" class="work"><h1>Hello</h1></div>
<div style="width: 100%" class=""><h1>Hello</h1></div>
<button onclick="changeColor()">Change second color by inserting class!</button>
function applyClass(elem_position, tagname, classname)
{
var div_elems = document.querySelectorAll(tagname);
for (var i = elem_position-1; i < div_elems.length;i++)
{
div_elems[i].className=classname;
}
}
Usage
Applies class some_class to div elements starting from position 3
applyClass(3,'div','some_class');
Related
When you write element.style = "..." in JavaScript in adds the style attribute to the element you add the style to. Is there a way to add a style without the style attribute, without any libraries?
If you can come up with a selector that targets the element, another option is to append a stylesheet that contains that selector:
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = 'div { color: blue; }';
<div>Some div</div>
It'd be more reliable if you're permitted to change the element in some way, like add a class or other attribute:
const div = document.querySelector('div');
const className = `_${('' + Math.random()).slice(2)}`;
div.classList.add(className);
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = `.${className} { color: blue; }`;
<div>Some div</div>
With JS, you can write anything to the DOM, including a <style> tag. So for example:
const el = document.getElementById('changeColor');
el.onclick = function(e) {
const s = document.createElement('style');
s.innerHTML = '.box { background-color: yellow; }';
document.querySelector('body').appendChild(s);
}
.box {
width: 150px;
height: 150px;
background-color: red;
color: white;
padding: 20px;
}
#changeColor {
margin: 10px 0;
}
<body>
<button type="button" id="changeColor">Change It</button>
<div class="box">This is a box</div>
</body>
Add a CSS class inside styles tags
Use the DOMContentLoaded event to add a class to the element when the document is loaded
Get the elment through its tag name
Use setAttribute method in vanillaJS to add the CSS class to your tag elment
In this way it could be more maintainable yoru code, because you change at css level and JS auntomaticly will put the value tanken from css class declared
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.styles {
color: red;
}
</style>
</head>
<body>
<p>Hello there</p>
<script>
let paragraph = document.querySelector("p")
document.addEventListener("DOMContentLoaded", () => {
paragraph.setAttribute("class", "styles")
})
</script>
</body>
</html>
So a little lost here, I'm not sure how to approach this, I've done the HTML and CSS but not sure how to do it in JS.
My HTML:
<!doctype html>
<html lang="en">
<head>
<title> Task 1 </title>
<meta charset="utf-8">
<script src="DomNodes.js"></script>
<style>
#output {
border: blue 5px solid;
padding: 10px;
margin-bottom: 10px;
margin-top: 10px;
width: 50%;
}
#output p {
padding:10px;
border: black 1px dashed;
}
</style>
</head>
<body>
<h2> TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree </h2>
<p> Type in text below, click add to add as paragraph. <button id="add"> ADD </button> </p>
<textarea id ="input" rows="10" cols="60">
</textarea><br>
<button id="delete">Delete Last Paragraph</button>
<br><br>
<h2> Added Paragraphs </h2>
<div id="output">
</div>
</body>
</html>
This is the code with little explain
<!doctype html>
<html lang="en">
<head>
<title> Task 1 </title>
<meta charset="utf-8">
<!--<script src="DomNodes.js"></script>-->
<script>
function myFunction() {
//get input user
var userInput=document.getElementById("input").value;
//clean text area
document.getElementById("input").value="";
//create paragraph
var para = document.createElement("p");
//assign value ->user input
var node = document.createTextNode(userInput);
//assign text at paragraph
para.appendChild(node);
//assign paragraph at div tag
var element = document.getElementById("output");
element.appendChild(para);
}
function remove_LastChild() {
//get div output
var select = document.getElementById('output');
//control if there are child into output div
if (select.childElementCount>0){
//select last paragraph and remove it
select.removeChild(select.lastChild);
}
else{
alert("Tehere are not paragraph!");
}
}
</script>
<style>
#output {
border: blue 5px solid;
padding: 10px;
margin-bottom: 10px;
margin-top: 10px;
width: 50%;
}
#output p {
padding:10px;
border: black 1px dashed;
}
</style>
</head>
<body>
<h2> TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree </h2>
<p> Type in text below, click add to add as paragraph. <button id="add" onclick="myFunction()"> ADD </button> </p>
<textarea id ="input" rows="10" cols="60">
</textarea><br>
<button id="delete" onclick="remove_LastChild()">Delete Last Paragraph</button>
<br><br>
<h2> Added Paragraphs </h2>
<div id="output">
</div>
</body>
</html>
I hope this hel you
I'm trying to execute a function by clicking on a span, but it tells me that it is undefined.
$(document).ready(function() {
function callTo(param) {
alert(param);
}
});
.file-up {
background: #f5f5f5 none repeat scroll 0 0;
border: 1px solid #ccc;
color: #383f45;
font-size: 12px;
margin-bottom: 10px;
padding: 6px;
font-size: 10px;
text-align: center;
text-transform: uppercase;
cursor: pointer;
}
<div>
<span class="file-up" onclick="callTo('test')">Click to call</span>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>
sample
</title>
</head>
<body>
<script>
function callTo(param) {
alert(param);
}
</script>
<div>
<span class="file-up" id="index" onclick="callTo('test')">
Click to call
</span>
</div>
</body>
This is a working example without using jQuery, just by vanilla javascript. Insert it and use it directly.
If you want me to post an answer which uses only jQuery for the stated task that you want to accomplish then please let me know.
This is code using jQuery, as you asked -
<!DOCTYPE html>
<html>
<head>
<title>
sample
</title>
</head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#index').click (function callTo() {
alert("Your values is :"+ $(this).data("value"));
});
});
</script>
<div>
<span class="file-up" id="index" data-value="test">
Click to call
</span>
</div>
Try to move your function definition away from $(documents).ready
<script>
function callTo(param) {
alert(param);
}
</script>
Or define event listener like
<script>
$(document).ready(function() {
$('.file-up').click(function() {
//action
});
});
</script>
(I'd better give it an id in this case and change the selector to #id instead of .file-up because other elements can have the same class applied)
JQuery beginner here. I'm trying to get a group of divs to change from red to blue when I click on them. When I click them again, I want the divs to change back to red. I tried using jQuery's animate() method (with the jQuery color plugin) to change the div's color. However, the code below only partially works.
$(document).ready(function(){
$("div").click(function() {
$("div").each(function() {
if (this.style.color !== "blue") {
$(this).animate({
color:'blue'
},1000);
} else {
this.style.color = "red";
}
});
});
});
When I click a div, the if statement works fine. The divs change to blue. However, when I click a div again, the divs don't change back to red. The else statement doesn't seem to work. Any ideas on my mistake? The else statement works when I replace $(this).animate({...}) with this.style.color = "blue"; which so I think I'm doing something wrong with the animate() method.
Here is the HTML file
<!DOCTYPE html>
<html>
<head>
<title> each() test1 </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
body{
background-color: #000000;
color: #ffffff;
}
div {
font-size: 3em;
color: #ff0000;
text-align: center;
cursor:pointer;
font-weight: bolder;
width: 300px;
}
</style>
</head>
<body>
<div> Click here </div>
<div> to iterate through </div>
<div> these divs </div>
</body>
<script src="theJavaScriptFile.js"> </script>
</html>
Just don't use blue or red color codes. It will get converted to RGB code.
For example this.style.color will be RGB(0,0,255) not blue so your expression always returns true no matter what color is it.
I create this example in different color mode for you to take a look https://jsfiddle.net/3tpncgr1/1/
Anyway, if you want to have special logic for particular color then keep using this approach. Otherwise, use class name instead of color code to determine. Because browsers always return rgb value for color attribute
I would manage it by using a active class to control the states.
In that case I would succes changing
$(document).ready(function(){
$("div").click(function() {
$.each( $(this).parent().children("div"),function() {
if (!$(this).hasClass('active')) {
$(this).addClass('active');
$(this).animate({
color:'blue'
},1000);
} else {
$(this).removeClass('active');
this.style.color = "red";
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title> each() test1 </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
body{
background-color: #000000;
color: #ffffff;
}
div.active{ }
div {
font-size: 1em;
color: #ff0000;
text-align: center;
cursor:pointer;
font-weight: bolder;
width: 300px;
}
</style>
</head>
<body>
<div id="containerOne">
<div> Click here </div>
<div> to iterate through </div>
<div> these divs </div>
</div>
<div id="containerTwo">
<div> Click here </div>
<div> to iterate through </div>
<div> these divs </div>
</div>
</body>
<script src="theJavaScriptFile.js"> </script>
</html>
I'm working on a Joomla website. Now I need a slider to change when someone hovers over a text link. I'm using some javascript. It's working on the first div with the id=slider, but not on the second div with id=slider in the article. Can someone tell me why it's doing this?
I'm using the following code in a custom code module for Joomla.
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<title>Untitled Page</title>
<style type="text/css" media="screen">
<!--
.boxVisible {
background-color: #eee;
display: block;
padding: 5px;
float: left;
border: solid 1px #000040
}
.boxHidden {
display: none;
}
-->
</style>
<script type="text/javascript">
<!--
function showHide(slider) {
theBox = document.getElementById(slider);
if (theBox.className == "boxVisible") {
theBox.className = "boxHidden";
} else {
theBox.className = "boxVisible";
}
}
//-->
</script>
</head>
<body bgcolor="#ffffff">
<p>More</p>
</body>
</html>
This is my article:
<div id="slider" class="boxVisible">{loadposition slider1}</div>
<div id="slider" class="boxHidden">{loadposition slider2}</div>
<p><br /><br /><br /> {loadposition java}</p>
IDs must be unique identifiers. For multiple elements, use class names.
Id's should be unique on a page.
You could wrap your slider divs in a wrapper div and use that as basis for iterating through your sliders something like this.
HTML:
<div id="sliders">
<div class="boxVisible"></div>
<div class="boxHidden"></div>
</div>
Javascript:
function showHide2(slider) {
var sliders = document.getElementById(slider).getElementsByTagName("div");
for (s in sliders) {
if (sliders.hasOwnProperty(s)) {
if (sliders[s].className == "boxVisible") {
sliders[s].className = "boxHidden";
alert('changed visible');
} else if (sliders[s].className == "boxHidden") {
sliders[s].className = "boxVisible";
alert('changed hidden');
}
}
}
}
showHide2("sliders");
the dom elements can't have the same id's! if you give the same id to the multiple dom elements, javascript will take only the first one.