I am trying to execute the javascript below and I am getting an undefined error. I am just trying to create a div with some text and place it before a span tag when the page loads.. I could be totally off base with my code though:
<script type = "text/javascript">
function MMinsertPhoneinheader() {
var div = document.createElement('div');
div.innerHTML = ("<span> <p> Get Detailed Pricing </p> <br> <p> <b> (866)682-7927 </b></p> </span>");
div.setAttribute('class', 'cust');
document.getElementsByTagName('span')[5].appendChild(div);
break;
};
MMinsertPhoneinheader();
</script>
Any help would be life saving. Sorry for the noob question. Thanks!
Here is the new code:
<script language="javascript">
function MMinsertPhoneinheader() {
var div = document.createElement('div');
div.innerHTML = ("<span> <p> Get Detailed Pricing </p> <br> <p> <b> (866)682-7927 </b></p> </span>");
div.setAttribute('class', 'cust');
document.querySelector(".toplinks").appendChild(div);
};
MMinsertPhoneinheader();
</script>
I am getting the Syntax Error on line 3.
var div = document.createElement('div');
Get rid of the break statement. That’s causing your problem.
Also, I’d recommend using document.querySelector rather than your getElementsByTagName(‘span’)[5].
That’s brittle. With document.querySelector(), you can just use a css selector.