Javascript .css not working nor jquery .blue

127 views Asked by At

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/

3

There are 3 answers

3
li_ On

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';
}
0
Alex Lavriv On

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');
1
Clyde W. Phillips Jr. On
// JS
document.querySelectorAll('pre').forEach(str => {str.style.color='blue';})

//jQuery
jQuery('pre').css('color','blue');