flr
January 9, 2011, 11:29pm
1
I am trying to change the background of a paragraph when the text on that paragraph is clicked.
The code looks like:
p= document.createElement(“p”);
p.onclick = function(){ p.setAttribute(“style”,"background:#306EFF ; " ) ; } ;
However it will not work.
What changes should I do in order to make it work?
When the event triggers the function, it doesn’t know anything about the p variable.
Instead, you can use the this keyword, which refers to the element that triggered the event, that being in this case the paragraph.
this.setAttribute(…);
Or, you can directly set the style attribute:
this.style = ‘…’;
AllanP
January 10, 2011, 12:25am
3
I have added a target div so that you can append the paragraph to an existing node on the page.
[HIGHLIGHT=“”]
<!doctype HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=windows-1252”>
<title>Add attributes to paragraph</title>
<script type=“text/javascript”>
<!–
window.onload= function() {
// create paragraph
var para=document.createElement(“p”);
var txtNode=document.createTextNode(“This is my paragraph. Click me”);
// add text node
para.appendChild(txtNode);
// add onclick handler
var styleString=“background-color:#306EFF ; cursor:pointer; color:#FFF ; font-weight:bold;”;
para.onclick = function(){ para.setAttribute(“style”,styleString) }
// get target object
var targDiv=document.getElementById(“myDiv”);
// append new paragraph
targDiv.appendChild(para);
}
//
//–>
</script>
</head>
<body>
<div id=“myDiv”>
</div>
</body>
</html>
flr
January 10, 2011, 11:32am
4
Thanks a lot for replays, I got it working.