Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById then calculate length

A fairly easy question I assume, but I'm only a beginner and I'm struggling to work this out for myself and I can't seem to find the answer on google.

I have a heading tag that I need to grab using javascript and then work out the length of, then edit the font size depending on the result.

Why is my code not working?

var titleElement = document.getElementById("myelement");

if(titleElement.length>10){
titleElement.style.fontSize = 16;
}

EDIT / ADDITION

I can't get it to work, even after your kind suggestion to add .innerHTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body onload="titleLengthShow()">
<h1 id="myelement">dfg adg earsh aaerg eaag erg aergethj5 yetfgg eg d</h1>

<script type="text/javascript">

function titleLengthShow(){
var titleElement = document.getElementById("myelement");

    if(titleElement.innerHTML.length>10){
        titleElement.style.fontSize = 16;
    }

}
</script>
</body>
</html>
like image 527
cloggy Avatar asked Nov 04 '25 06:11

cloggy


2 Answers

var titleElement = document.getElementById("myelement");

if(titleElement.innerHTML.length > 10){
  titleElement.style.fontSize = "16px";
}

should work. innerHTML gives you the containing text (actually html).

if you have formating inside your heading tag it will also count those formating tags. instead you can use .textContent instead of .innerHTML, although this won't work in older IEs. for older IE versions .innerText should work.

var length = (titleElement.textContent || titleElement.innerText ||
              title.innerHTML).length;

shoudl work for the common browsers.

like image 126
Christian Avatar answered Nov 06 '25 20:11

Christian


You need to check the length of titleElement.innerHTML.

I strongly suggest to look into jQuery to do such things.

like image 40
Bernhard Avatar answered Nov 06 '25 19:11

Bernhard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!