document.getElementById("xxx").style [duplicate] - javascript

This question already has answers here:
How to apply CSS style to all elements with same ID using one button?
(6 answers)
Closed 6 years ago.
I want to use getElementById("xxx").style.color = "xxx".
With this I want to change some css value. But the problem is when i use this and test all same id with this but it does't effect all id and effects only the first one.
Sample code is as follow:
<html>
<body>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<div id = "test">Test</div>
<script>
document.getElementById("test").style.color = "blue"
</script>
</body>
</html>
What should i do to change all 4 Test to color blue.
AnyIdea pls.
Thanks

An ID must be unique in an HTML document. Write valid HTML.
To represent multiple, related elements: use a class.
You can then use getElementsByClassName or querySelectorAll to get an array-like object which you can use a for loop to access each element in turn.
var elements = document.querySelectorAll(".test");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "blue";
}
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
Alternatively, write a stylesheet with a descendant combinator and toggle the classes on a containing element.
document.getElementById("container").classList.add("foo");
.test { color: black; }
.foo .test { color: blue; }
<div id="container">
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
</div>

As stated before, an ID must be unique. If you want to give multiple DOM-elements the same style just use 'class'.
you could try this:
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
var divList = document.getElementsByClassName("test");
for (var i = 0; i < divList.length; i++) {
divList[i].style.color = "red";
}
</script>
</body>
</html>
to change the style using javascript.

There are two problems with your code :
id must be unique, so you should use eg. class instead
you should loop across the different elements that are selected
This is my prefered way to correct those two problems :
<html>
<body>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<div class="test">Test</div>
<script>
Array.prototype.slice.call(
document.getElementsByClassName("test")
).forEach(function(element) {
element.style.color = "blue"
});
</script>
</body>
</html>
See also this Fiddle.

For jQuery Solution
You cannot use same id for performing same operation on all the elements
You can use class name and add style using jquery like
$(".className").css("color","blue");

Related

How do I append an element after a specific element using jquery with an object as the target?

I want to append an element of H2 <h2>H2</h2> to the html as shown below
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="a">
<h1>H1</h1>
<!--I want to add H2 here-->
<h3>H3</h3>
</div>
<div id="b">
</div>
</body>
</html>
I query the div like this var mydiv = $("#a")[0]; and then I want to append <h2>H2</h2> inside myDiv, but after <h1>H1</h1> OR before <h3>H3</h3>. I have played around a bit with after(), insertAfter(), before(), insertBefore() with no luck, because i want to target and use the object 'myDiv' and not the whole html page.
EDIT: Some things I have tried
I have tried the following:
var myDiv = $("#a")[0]
$(myDiv).append("<h2>H2</h2>")
This adds the element to the end of the div
Also tried this:
$("h1").after("<h2>H2</h2>")
This adds <h2>H2</h2> after every <h1>H1</h1> which is not what I need to do, I need to add <h2>H2</h2> only inside the selected div which in this case is myDiv
Use jQuery#after and jQuery#find
var myDiv = $("#a")[0];
$(myDiv).find('h1').after("<h2>H2</h2>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a">
<h1>H1</h1>
<!--I want to add H2 here-->
<h3>H3</h3>
</div>
<div id="b"></div>
or
$("#a").find("h1").after("<h2>H2</h2>");
or
$("#a h1").after("<h2>H2</h2>");
Your code is correct, only need change the selector adding h1 in the myDiv selector.
Example:
var myDiv = $("#a h1")[0]
$(myDiv).after("<h2>H2</h2>")

Style for loop with CSS

Im supposed to make 8 boxes and style them each, make the boxes with for loop. Every odd box should look different then the others. I have tried to make an id, but when i use the id in CSS, it wont do anything. Can someone help?
Here is the code i have:
var text = "";
var i;
for (i = 1; i < 10; i++) {
text += "Box number " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
.demo {
border: black;
}
<p id="demo"></p>
As volodymyr says use css nth-child property.
In javascript you can accomplish this in the following manner:
for(let i = 0; i < document.querySelectorAll('.class').length; i += 2){
document.querySelectorAll('.class')[i].style.color = 'red';
}
<div class="class">1</div>
<div class="class">2</div>
<div class="class">3</div>
<div class="class">4</div>
<div class="class">5</div>
<div class="class">6</div>
<div class="class">7</div>
<div class="class">8</div>
<div class="class">9</div>
<div class="class">10</div>
This uses a for loop which iterates over every odd element, and then applies styles via javascript. Usually a pure CSS implementation would be preferable though.
You can use css nth-clild property
.class:nth-child(odd) {background: red}
<div class="class">1</div>
<div class="class">2</div>
<div class="class">3</div>
<div class="class">4</div>
<div class="class">5</div>
<div class="class">6</div>
<div class="class">7</div>
<div class="class">8</div>
<div class="class">9</div>
<div class="class">10</div>
Your css references the "class" demo selector but your HTML uses an "id" property id='demo'. Change either one to match the other.

Changing HTML div's background colour when it is clicked using JavaScript without jQuery

Trying to implement a very simple feature, using only JavaScript without jQuery. I want the background of the HTML div with id='tags' to change, when I click on it.
document.getElementById('tags').addEventListener('onclick', function() {
this.style.backgroundColor = 'red';
});
<body>
<div id="tags">Item1</div>
<div id='tags'>Item2</div>
<div id='tags'>Item3</div>
</body>
Identiifiers in HTML must be unique, Use a common CSS class to instead.
Use querySelectorAll() to target them, as it will return a list, iterate it and bind event handlers
remove prefixed "on"
document.querySelectorAll('.tags').forEach(function(element) {
element.addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
})
<div class="tags">Item1</div>
<div class='tags'>Item2</div>
<div class='tags'>Item3</div>
A few issues here:
your script is (or was before you edited the question) executing before the <div> elements are added to the document; the <script> needs to be placed after the <div>s in your HTML source code.
you can't have multiple elements with the same id. use class="tags" instead.
the event is "click" not "onclick"
Here's what i'd do instead:
<body>
<div class="tags">Item1</div>
<div class="tags">Item2</div>
<div class="tags">Item3</div>
<script>
for (let x of document.getElementsByClassName('tags')) {
x.addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
}
</script>
</body>

How to change the colour of a div element when clicked?

I have a this html page, Whenever the element with class name FreeSeat is clicked I want to change the colour of that div element.Below is my html page
<html>
<head>
<title>
QuickBus
</title>
<link type="text/css" rel="stylesheet" href="Seat.css">
</head>
<body>
<div id="Bus">
<div class="Row">
<div class="FreeSeat" ></div>
<div class="FreeSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
<div class="ResSeat" ></div>
</div>
</div>
<body>
</html>
It will be very helpful if anyone can help me out with this .
Considering that you want to use pure JS and not any library, you'd have to manually add event listeners to your classes.
And it has been solved for a similar problem here
var freeclass = document.getElementsByClassName("FreeSeat");
var myFunction_Free = function() {
this.style.color = "blue";
}
for(var i=0;i<freeclass.length;i++){
freeclass[i].addEventListener('click', myFunction_Free, false);
}
But for your case, here's a working fiddle
JQuery is amazing for these sorts of things.
Say you have a div with id 'box1'
<div id='box1'></div>
Style it with css
#box1 {
width:100px;
height:100px;
background-color:white;
border:1px solid black;
}
Using JQuery, you can make this call:
$( "#box1" ).click(function() {
$('#box1').css('background-color', 'red');
});
And now whenever your div is clicked, the colour will change, you can customise this however much you like.
Here is a JSFiddle demo.
Also, since you didn't specify exactly what you want to change the colour of, in my example jquery, it is telling the browser that when a div with an id of box1is clicked, change the background-color of the div with an id of box1, you can change anything though.
If you have a <p> tag you can change that too when the div is clicked, hope this helped!
You can use the following method to change the background color of an element by class:
const free_seat = document.getElementsByClassName('FreeSeat');
free_seat[0].style.backgroundColor = '#ff0';
Each element can be referenced by its index:
free_seat[0] // first div
free_seat[1] // second div
Therefore, we can create a function that will be called whenever the click event is delivered to the target:
const change_color = () => {
this.style.backgroundColor = '#ff0';
};
for (let i = 0; i < free_seat.length; i++) {
free_seat[i].addEventListener('click', change_color);
}
Note: You can also use document.querySelectorAll('.FreeSeat') to obtain a NodeList of elements of a certain class.
You can use simply the css focus pseudo-class for this:
#foo:focus {
background-color:red;
}
<div id="foo" tabindex="1">hello world!</div>
Dont forget to set the tabindex.

How to get element inside other specific element using its id and getElementById?

I'm writing a really big script and performance is a big deal for me, especially that it has to work as fast as it can in IE (employer requirements). I have to do some innerHTML and stuff like that but for an element that has some class or id and is nested into some other element with some id or class.
I can do it using querySelector(), but as I saw in some performance tests for IE, querySelector is a few times slower than getElementById or even getElementsByClassName(). That's why I want to use these getElement... functions.
Here's an example:
<div id='firstID' class='someClass'>
<div id='secondID' class='someClass2'></div>
</div>
<div id='thirdID' class='someClass'>
<div id='secondID' class='someClass2'></div>
</div>
And I want to get this secondID element but it has to be one in firstID element. Like I said before, I can use querySelector('#firstID #secondID'); or a jQuery equivalent but it is much slower than getElementById() so I'm asking you how can I translate it into getElementById?
P.S. In my tests getElementById was performed 1 300 000 times per second whereas querySelector was perfomed about 400 000 times. So, you see where I'm getting with that.
Never ever use the same ID twice ( ID stand for identity and two elements can't have the same identity ). You can use the class name instead
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="a">
<div id="b" class="someClass2"></div>
</div>
<div id="c">
<div id="d" class="someClass2"></div>
</div>
<script type="text/javascript">
var parent = document.getElementById("a");
var childs = parent.getElementsByClassName("someClass2");
var firstSomeClass2Element = childs[0];
firstSomeClass2Element.innerHTML = "Example";
</script>
</body>
</html>
More about ID:
The Element.id property represents the element's identifier,
reflecting the id global attribute.
It must be unique in a document, and is often used to retrieve the
element using getElementById. Other common usages of id include using
the element's ID as a selector when styling the document with CSS.
https://developer.mozilla.org/es/docs/Web/API/Element/id
Here is the solution you need but is very very bad
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="a">
<div id="b" class="someClass2">a</div>
</div>
<div id="c">
<div id="b" class="someClass2">s</div>
</div>
<script type="text/javascript">
var parent = document.getElementById("a");
var childs = parent.childNodes;
for (var i = 0; i < childs.length; i++) {
if (childs[i].nodeType == Node.ELEMENT_NODE) {
if(childs[i].id == "b") {
console.log("Done");
}
}
}
</script>
</body>
</html>
Example with attached function
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="a">
<div id="b" class="someClass2">a</div>
</div>
<div id="c">
<div id="b" class="someClass2">s</div>
</div>
<script type="text/javascript">
HTMLElement.prototype.findId = function(_id) {
var childs = this.childNodes;
for (var i = 0; i < childs.length; i++) {
if(childs[i].nodeType == Node.ELEMENT_NODE) {
if(childs[i].id == _id) {
return childs[i];
}
}
}
return null;
}
// Usage Example
var parent = document.getElementById("a");
console.dir(parent.findId("b"));
</script>
</body>
</html>

Categories