How to change the background colour if a paragraph on click on that paragraph

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.


Or, you can directly set the style attribute: = ‘…’;

I have added a target div so that you can append the paragraph to an existing node on the page.

<!doctype HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>


<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
// 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


<div id=“myDiv”>



Thanks a lot for replays, I got it working.