0

I'm having all sorts of trouble styling simple html in js and jQuery It seems a jsfiddle is used here to illustrate. I am new to it and don't see console output or the desired results so I ask this question to learn more about how so can help; I did search so for .css not working and variations

javascript

    .css() is jQuery.
    .style is js.

document.getElementsByTagName('pre').text.css("color: blue;"); jquery: const preSentences = $("pre").text().split(".") console.log({preSentences})

    //no err no workee in chrome

// preSentences.forEach(function(str) { $(this).css("color: blue; border: 1px solid black")}); // $.each(preSentences, function(str) { $(this).blue }) // preSentences[1].style("color: blue; border: 1px solid black");

the fiddle is here I think - I tried the embed link and it doesn't show up: https://jsfiddle.net/Lz8nh50o/

  • `document.getElementsByTagName('pre').text.css("color: blue;")` not even close to valid use of native DOM methods. - Did you check the developer tools console for errors? – Jaromanda X Nov 12 '17 at 02:00

3 Answers3

1

getElementsByTagName will return an array of tags, and you have to loop through each one to set the style. Also, you are using .css() but that is a jQuery function. You have to use style.

Try this:

var preTags = document.getElementsByTagName('pre');
for(var i=0; i<preTags.length; i++){
  preTags[i].style.color='blue';
}
li_
  • 124
  • 1
  • 9
1

You can iterate though the htmlCollention with ES6 for-of loop, it seems cleaner.

let list = document.getElementsByTagName('pre')

for (let currentElement of list){
    currentElement.style.color ='blue';
}

jQuery equivalent is

jQuery('pre').css('color','blue');
Alex Lavriv
  • 321
  • 1
  • 10
0
// JS
document.querySelectorAll('pre').forEach(str => {str.style.color='blue';})

//jQuery
jQuery('pre').css('color','blue');
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
  • document.querySelectorAll('pre').forEach(str => str.style.color='blue') . In this case you can even drop the curvy brackets and the semicolon. – Alex Lavriv Nov 12 '17 at 06:30