简体   繁体   中英

DOM manipulation - Center H1 element using javascript

How can I center my h1 using javascript?

h1 is <h1>Instrument track Recommendations</h1> , I tried below and it does not work.

var centeredH1 = document.getElementsByTagName("h1");
centeredH1.style.textAlign = "center";`

I know it would work with an ID using document.getElementById("h1id"); if I had one but I don't have an ID to work with.

getElementsByTagName returns an array-like object. If you have only one element, it will return an array-like object with one element. You need to get the [0] indexed element in that object. But as you have mentioned, it will be better to work with id in this case, if you want to attach styles only to one element.

 var centeredH1 = document.getElementsByTagName("h1")[0]; // -------------------------------------------------^^^ centeredH1.style.textAlign = "center"; 
 <h1>Test</h1> 

DEMO

JAVASCRIPT

var h1s = document.getElementsByTagName("h1");
h1s[0].style.textAlign="center";

HTML

<h1>
THIS IS TO BE CENTERED
</h1>

You need to access first element from array returned by javascript getElementsByTagName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM