-3
body#page-mod-quiz-attempt
|- div#page-content
  |- div.col.md-3

I need to change div.col.md-3 add col-sm-12 and col-xs-12

I use js:

var Quiz = document.getElementById('page-mod-quiz-attempt');
var Contenz = Quiz.document.getElementById('page-content');
Contenz.getElementsByClassName("col-md-3").className += ' col-xs-12 col-sm-12';

and jQuery:

$(document).ready(function() {
  $('#page-mod-quiz-attempt #page-content div.col-md-3')
    .removeClass()
    .addClass('col-md-3 col-xs-12 col-sm-12');
});

But failed. Maybe I missed something. I prefer pure JavaScript route if possible.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38

2 Answers2

0

your html definition uses div.col.md-3 but your js uses col-md-3 so first check for typos.

Next, var Contenz = Quiz.document.getElementById('page-content'); will return an error Uncaught TypeError: Cannot read property 'getElementById' of undefined, so if var Quiz = document.getElementById('page-mod-quiz-attempt') is not needed. Just use var Contenz = document.getElementById('page-content');

Then, Contenz.getElementsByClassName('col-md-3'); returns an array with the class. so Contenz.getElementsByClassName('col-md-3').className; is undefined. Instead Contenz.getElementsByClassName('col-md-3')[0] will be the html that is using that class.

Finally you have this: var Contenz = document.getElementById('page-content'); Contenz.getElementsByClassName('col-md-3')[0].className += ' col-xs-12 col-sm-12'; Which will do what you were asking. https://jsfiddle.net/onbjhppm/2/

UPDATE: per the comment form OP

If you need to use id="page-mod-quiz-attempt" as the unique identifier, do this instead:

var Quiz = document.getElementById('page-mod-quiz-attempt'); Quiz.getElementsByClassName('col-md-3')[0].className += ' col-xs-12 col-sm-12'; https://jsfiddle.net/onbjhppm/3/ Or else add a class identifier to id="page-content" element and chain getElementsByClassName to get to the one you want

Note: getElementById is only available on document. In order to chain them you will have to create your own function chaining getElementById

sgraham
  • 143
  • 8
  • i need the "page-mod-quiz-attempt" to identify the page i'm targetting. if i don't use it, all the page on the site will use the script. – Kompli Tivi Sep 21 '17 at 00:26
0

I think changing your jQuery as follows will resolve your issue, you also forgot a period before your class name in the first selector ;) ...

$(function() {
  $('#page-mod-quiz-attempt #page-content div.col-md-3').addClass('col-xs-12').addClass('col-sm-12').removeClass('.col-md-3');
});
iPzard
  • 2,018
  • 2
  • 14
  • 24