Reputation: 4491
document.getElementsByClassName('big-button')[0,1,2].style.display = "inline-flex";
I'm trying to apply that style to all/any element that matches the class name. I tried [0,1,2]
because I just have 3 instances, but it only targets the third instance.
This does not need to work in production. Just in Chrome. It's just prototyping.
Upvotes: 0
Views: 70
Reputation: 19372
There are N counts of ways to achieve it.
function borderRed(className, elementIndexes) {
elementIndexes.forEach(index => {
document.getElementsByClassName(className)[index].style = "border: 1px solid red";
});
}
borderRed('big-button', [0, 2, 4]);
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>
var buttons = document.getElementsByClassName('big-button');
buttons[0].style = 'border: 1px solid red';
buttons[2].style = 'border: 1px solid red';
buttons[4].style = 'border: 1px solid red';
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>
$(function() {
$('.big-button').slice(0, 3).css('border', '1px solid red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>
document.querySelector
var buttons = document.querySelectorAll('.big-button:nth-child(1),.big-button:nth-child(3),.big-button:nth-child(5)');
buttons.forEach(button => button.style = 'border: 1px solid red');
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>
Upvotes: 1
Reputation: 370729
When you put commas between values inside square brackets, you're invoking the comma operator, which evaluates each item in the comma-separated list, and then evaluates to the final value in the list. Thus, your code evaluates to [2]
, or only the third item. Generally, if you have an array-like object on the left hand side, you need to provide a single value in the following square brackets, like [0]
or [1]
.
If you want to apply that style to the first three elements of the list, you'll have to explicitly iterate over them. For example, one possible implementation is:
const buttons = document.querySelectorAll('.big-button');
const firstThreeButtons = Array.prototype.slice.call(buttons, 0, 3);
firstThreeButtons.forEach(button => button.style.display = 'inline-flex');
Upvotes: 7