0

I have an Javascript array of indexes like so [0, 2]

And a bunch of paragraph elements like so

<div>
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

What would be a succinct way to add a css class to the paragraphs whose index appears in the array? In this case I expect a class to be added to first and third paragraphs.

Output expected:

<div>
  <p class=“red”>some text</p>
  <p>some more text</p>
  <p class=“red”>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>
4
  • use :nth-child()...... Commented Apr 25, 2019 at 6:27
  • 1
    Might as well post my take: jsfiddle.net/khrismuc/gxnq24fs Commented Apr 25, 2019 at 6:34
  • 1
    What @cloned meant is that SO is not a code writing service, we help with written code, and when reading How to Ask you'll see it is expected the poster make an effort of their own. Commented Apr 25, 2019 at 6:35
  • Edited my fiddle to include element check. Commented Apr 25, 2019 at 6:54

6 Answers 6

3

Use querySelectorAll and check the index:

const arr = [0, 2];
const parent = document.getElementById("parent");
parent.querySelectorAll("p").forEach((elem, idx) => arr.includes(idx) ? elem.classList.add("red") : elem);
.red {
  color: red;
}
<div id="parent">
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

Older browsers:

var arr = [0, 2];
var parent = document.getElementById("parent");
parent.querySelectorAll("p").forEach(function(elem, idx) {
  if (arr.indexOf(idx) > -1) {
    elem.classList.add("red");
  }
});
.red {
  color: red;
}
<div id="parent">
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

Sign up to request clarification or add additional context in comments.

5 Comments

Given that IE is not completely dead, making a note it won't work on it is appropriate (even if it is dead for you, many still need to support it).
OK @LGSon, I'll add an ES5 version.
@LGSon we can avoid that indexOf or includes, please consider the second example in my answer
@AnkitAgarwal I know that, still, your solution might backfire if an index in the array doesn't have an element.
@JackBashford Well, forEach on nodelist won't work either in IE and older browsers
3

Just a forEach loop is enough.

var arrIndex = [0, 2];
var elems = document.querySelectorAll('div p');

arrIndex.forEach(function(p){
	elems[p] && elems[p].classList.add('red');
})
.red {
  color: red;
}
<div>
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

3 Comments

This is how to do this: no NodeList.forEach, and no index check. Iterating over the array instead of the elements is more efficient by a mile.
@LGSon I have edited the answer.
@ChrisG Since we got this out of the world, I deleted my comments as they have no future value...and will with this too soon.
0

The one way is to select all the elements with that <p> element and then check that index of that particular element exist in the array or not:

var arrIndex = [0, 2];
var elems = document.querySelectorAll('div p');
for(i=0; i<elems.length; i++){
  if(arrIndex.indexOf(i) !== -1){
    elems[i].classList.add('red');
  }
}
.red {
  color: red;
}
<div>
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

Avoid using includes() as it is not supported by IE browser and old JS version browsers

Another way is to just loop the index array to add red class:

var arrIndex = [0, 2];
for(var i=0; i<arrIndex.length; i++){
 document.querySelectorAll('div p')[arrIndex[i]].classList.add('red');
}
.red {
  color: red;
}
<div>
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

Comments

0

Get all the paragraph using document.querySelectorAll. Traverse the array and add class to the required paragraph

var a=document.querySelectorAll('p');
var arr=[0,2]
for(let i=0;i<a.length;i++)
{
if(arr.indexOf(i)>-1)
a[i].classList.add("red");
}
.red
{
color:red
}
<div>
<p>some text</p>
<p>some more text</p>
<p>some sample text</p>
<p>some text here</p>
<p>some great text</p>
</div>

1 Comment

Should be i == 2 not 3.
0

If they are always siblings then you can use :nth-child() pseudo-class selector. Iterate over the array and generate the selector to get elements based on the selector and iterate over the selected elements to add class.

var index = [0, 2];

// generate the selector
var selector = index.map(v => `div p:nth-child(${ v + 1 })`).join();

// get elements using the selector
// iterate and add class
document.querySelectorAll(selector).forEach(e => e.classList.add('red'))
.red {
  color: red;
}
<div>
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

NOTE : It's an ES6 solution.

Comments

0
<div>
  <p>Some text</p>
  <p>Some more text</p>
  <p>Some sample text</p>
  <p>Some text here</p>
  <p>Some great text</p>
</div>

.red{
    color: red;
 }


const arr = [0,2]
const para = document.querySelectorAll('p')

arr.forEach(function(arr){
  para[arr].classList.add('red')
})

1 Comment

This is the same as vikasgupta's answer, without the NPE check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.