cloggy
cloggy

Reputation: 175

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>

Upvotes: 4

Views: 48168

Answers (3)

user1954492
user1954492

Reputation: 495

change

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

to

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

Upvotes: 1

Christian
Christian

Reputation: 3721

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.

Upvotes: 3

Bernhard
Bernhard

Reputation: 8831

You need to check the length of titleElement.innerHTML.

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

Upvotes: 1

Related Questions