? Change css (style) using plain javaScript based on text length in HTML 4.1
? Learning { Using http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript/196038#196038 } ? Learning how to use vanila JS to apply css (style) on a paragraph based on the length of the text in the <p>. Similar to : http://stackoverflow.com/questions/13644930/how-to-detect-when-multiple-lines-are-occurring-in-a-div . Need old way for FF pre 29. PLAIN javascript + css & html Does_not work as of 2014.07.21
by positive x
HTML
<aside>
<p>This is a plain - old paragraph.</p>
<p id='p_id1'>This is the p_id1 (blue) p</p>
<p id='p_id2'>This is the p_id2 (really l o n g ___ R E D ) paragraph . </p>
<p class='styletest'>This is a short class= p</p>
<p class='styletest'>This is other class= (really long _ R E D) paragraph .</p>
</aside>
<script>window.addEventListener('onload', style_byID_Blue_short_p);</script>
<script>window.addEventListener('onload', style_byClass_RED_Long);</script>
CSS
/* ? Change element's css _style based on <p> text length ? Use plain javaScript { no external library } ; + css ; & html 4.1 for pre 29 FireFox . ref: <http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript/196038#196038> */ /* This is NOT working as of 2014.07.21 */
body {background:#222; color: #111}
aside {padding: 2em; background: #eee}
.blue {color: #117;}
.green {color: #161;}
.red {color: #511;}
JavaScript
/* TESTing 1 getElementById('idname') way */
function style_byID_Blue_short_p () {
var textIn = document.getElementById('p_id1');
var txtLen = textIn.innerHTML.length;
if( txtLen<30 ){
textIn.className += ' blue'; //turn it blue
alert('here is style_byID_Blue_short_p that IDS blue!'); //for testing
} else {
textIn.style.color = '#511'; //turn it red
alert('style_byID_Blue_short_p that is red.'); //for testing
}
}
/* TESTing 2 getElementById('idname') way */
function style_byID_Blue_short_p () {
var textIn = document.getElementById('p_id1');
var txtLen = textIn.innerHTML.length;
if( txtLen<30 ){
textIn.className += ' blue'; //turn it blue
alert('here is style_byID_Blue_short_p that IDS blue!'); //for testing
} else {
textIn.style.color = '#511'; //turn it red
alert('style_byID_Blue_short_p that is red.'); //for testing
}
}
/* other way: document.getElementsByClassName("styletest")
& ele.classList.add 'red'; */
function style_byClass_RED_Long () {
var textIn = document.getElementcByClassName('styletest');
var txtLen = textIn.innerHTML.length;
if( txtLen<30 ){
textIn.style.color = '#161'; // turn it green
alert('here is style_byClass_RED_Long that is green.'); //for testing
} else {
textIn.className += ' red'; //turn it red
alert('here is style_byClass_RED_Long that IS red!'); //for testing
}
}