GetElementById then calculate the length

Quite a simple question I'm guessing, but I'm just a beginner and I'm struggling to do this for myself and I can't seem to find an answer on google.

I have a title tag that I need to grab using javascript and then work out the length and then edit the font size based 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>

      

+3


source to share


3 answers


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

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

      

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

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



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

      

shoudl works for common browsers.

+2


source


change

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

      



to

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

      

+1


source


You need to check the length titleElement.innerHTML

.

I highly recommend looking into jQuery for doing this kind of thing.

0


source







All Articles